2012-12-09 40 views
0

我对JavaScript非常陌生,类和方法的工作方式让我感到困惑。使用类中的变量调用类方法的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); 

或者类似的东西,东西线。我非常困惑,并且认为我正在做的事情都是错误的。

回答

2

我想你想somwthing这样的:

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);它创建一个空的对象,并在对象的上下文中执行的功能。

+1

sumUp/addUp为什么需要使用未使用的参数?似乎毫无意义。 – johusman

+0

@ johusman当然他们不会受伤。 –

+0

注意'new'也设置了对象的'[[prototype]]' –

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(); 
相关问题