0

我对 javascript 非常陌生,类和方法的工作方式让我感到困惑。

基本上我有这样的代码:

function container(x, y, z) {
  this.x = x;
  this.y = y;
  this.z = z;

  this.sumUp = function addUp(x, y, z) {
    var a = x + y + z;
  };
}

我想要做的是在我的代码的其他地方使用容器中定义的函数,使用容器中的值。我该怎么做呢?

类似的东西

container1 = new container (1, 2, 3);
container.sumUp(this.x, this.y, this.z);

或类似的东西。我很困惑,认为我把整件事都搞错了。

4

2 回答 2

2

我想你想要这样的东西:

function Container(x, y, z){
  this.x = x;
  this.y = y;
  this.z = z;

  this.sumUp = function addUp(x, y, z){
    alert(this.x + this.y + this.z);
  };
}

container_instance = new Container(1, 2, 3);
container_instance.sumUp();

但我建议:

function Container(x, y, z){
  this.x = x;
  this.y = y;
  this.z = z;
}

Container.prototype.sumUp = function addUp(x, y, z){
  alert(this.x + this.y + this.z);
};

container_instance = new Container(1, 2, 3);
container_instance.sumUp();

这就是它的工作原理(简短):

在 JavaScript 中objects,它们就像哈希:

var obj = {
  'a': 1,
  'b': 2,
  'c': 3
};

您可以通过键获取或设置值:

alert(obj.a); // alerts 1
alert(obj['a']); // same thing
obj['c'] = 4;

在您的情况下Container,函数将构建您的对象。当你这样做时new Container(1, 2, 3);,它会创建一个空对象,并在对象的上下文中执行函数。

于 2012-12-09T15:31:50.137 回答
1
function Container(x, y, z){
  this.x = x;
  this.y = y;
  this.z = z;
}
// There is no point to put parameters there since they are already instance variables.
Container.prototype.sumUp = function addUp(){
  alert(this.x + this.y + this.z);
};

container_instance = new Container();
container_instance.sumUp();
于 2012-12-09T15:34:28.713 回答