繁体   English   中英

Javascript使用类中的变量调用类方法

[英]Javascript calling a class method using variables in the class

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

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM