0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Why would sumUp/addUp need to take parameters that aren't used? Seems pointless.
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.