2

if I set a prototype value and make two instances

then update the prototype value in one instance

now other instance prototype value does not update, why?

code is

var A = function() {

}
A.prototype.u = 2;

var a = new A();

var b = new A();

a.u = 4
alert(a.u) // 4
alert(b.u) // 2

it's so unreasonable, it's prototype value not this value. right?

4
  • When doing assignment, the prototype chain isn't used, the property is only searched for on the object itself and if not found, a new property is added, masking the one on the prototype. Commented Jan 24, 2015 at 8:20
  • @RobG so I cannot update a prototype value in method, like global var? Commented Jan 25, 2015 at 11:12
  • Yes you can, but not the way you are trying to do it. You need to assign to A.prototype.u as in Quentin's answer. Commented Jan 25, 2015 at 11:40
  • @RobG do you think about to set prototype = {u:[11]}, then change it in instance, just not to type constructor name and prototype Commented Jan 25, 2015 at 11:49

1 Answer 1

6

You aren't "updating the prototype value". You are writing the new value to the local object and not to the prototype chain. The local property masks the one higher up the chain.

alert(a.u); looks at a, finds a u and alerts it.

alert(b.u); looks at b, doesn't find a u, looks up the prototype chain, finds a u and alerts it.

Compare:

var A = function() {

}
A.prototype.u = 2;

var a = new A();

var b = new A();

a.u = 4;
A.prototype.u = 6;
alert(a.u);
alert(b.u);

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

6 Comments

alert(b.u) // 2 <-- 6?
6 is right, since b.u is searched first -> not found -> prototype is then searched -> found -> 6. @Quentin's answer says 2 which is not right
@Quentin if I write a.x = function(){A.prototype.u = 6} it doest not work, why?
@Roy — Because you are either still masking it locally or because you don't call the method before you test the value of u.
@Roy—that just assigns a function to a.x. Until you call it (i.e. a.x()), the value of A.prototype.u won't change.
|

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.