简体   繁体   中英

Javascript calling a class method using variables in the class

I'm incredibly new to javascript and the way classes and methods work are confusing me.

Basically I have code like this:

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;
  };
}

What I want to do is elsewhere in my code use the function defined within the container, using the values in container. How do I actually go about doing this?

Something along the lines of

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

Or something like that. I'm very confused and thinking I'm going about the whole thing wrong.

I think you want somwthing like this:

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

But I recomend:

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

That is how it works (short):

In JavaScript you have objects , they are like hashes:

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

And you can get or set values by keys:

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

In your case Container is function which will build your object. When you do new Container(1, 2, 3); it creates an empty object, and execute the function in the context of the object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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