0

My understanding is that things on the prototype chain are only created once per object and that to create instance variables, one must use this. Is this correct?

For example:

function Foo () {
    this.some_instance = "hello";
}
Foo.prototype.some_static = "hi";

Implementation

var foo1 = new Foo();

var foo2 = new Foo(); 

Making a foo1 and a foo2 will create two values of hello but only one of hi.

Is this correct?

13
  • 1
    Yes the some_static variable will not be recreated for each instance and will exist on the prototype chain Commented Nov 3, 2013 at 1:23
  • This sort of thing could be tested very easily. Commented Nov 3, 2013 at 1:24
  • 1
    +1 @megawac, this would be a helpful read Commented Nov 3, 2013 at 1:24
  • the bigger question, was how to create instance variables with out using this, is it possible? I have a framework that create "classes" that I'm trying to update. Commented Nov 3, 2013 at 1:25
  • Which library are you trying to update Commented Nov 3, 2013 at 1:26

2 Answers 2

3

Short answer: Yes.

Proof:

function Foo () {
    this.some_instance = "hello";
}

var foo1 = new Foo();
Foo.prototype.some_static = "hi"; // in between
var foo2 = new Foo();

foo1.some_static === foo2.some_static; // return true
Sign up to request clarification or add additional context in comments.

2 Comments

Thats a poor test a better test would be Foo.prototype.some_static = {a:1}
I agree with megawac, that only proves that "hi"==="hi" you can define some_static as this.some_static, assign "hi" to it and the === will still be true. As megawac pointed out you can notice the sharing when you have mutable objects as your property value because assigning values to a property will cause JS to not look up on the prototype chain. Instead it'll just create that property on the instance and assign the value to it. foo1.some_static=... will create some_static on foo1 instance. stackoverflow.com/a/16063711/1641941
2

Well, making a foo1 and a foo2 won't create any values of "hi". The "some_static" variable with the value "hi" was already created, in the Foo prototype object, before you created foo1 and foo2.

When you create objects that use the Foo prototype, and you reference their "some_static" property, it will look in the objects themselves first. If the objects don't have a "some_static" property, it will look for it in their prototype object.

But yes, if you want to create a property that's unique to each object that uses the same prototype, you should set it on the object itself, not the prototype. You can do that by setting "this.some_instance" from inside one of the object's methods, or by setting "foo1.some_instance" from outside.

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.