我对 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);
或者类似的东西。我很困惑,认为我把整件事搞错了。
最佳答案
我想你想要这样的东西:
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 中,你有对象
,它们就像哈希值:
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);
时,它会创建一个空对象,并在该对象的上下文中执行该函数。
关于Javascript 使用类中的变量调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13788791/