0

Given the following setup, where obj inherits the property name from x

var x={name:"sameer"};
var y=Object.create(x);
y.name="pathak";
alert(y.__proto__.name)

i need to know why assigning property doesn't change the property in prototype since with . operator javascript consults the prototype chain and if it finds the similar property it should either replace or regect the change isn't it??Or is it because the property foo in prototype has writable attribute set to false??

Maizere
  • 33
  • 5
  • 2
    Assigning a property doesn't go up the prototype chain, it *just assigns the property*. The prototype isn't involved. – user229044 Sep 16 '13 at 05:36
  • Each object created from a prototype gets its own copy of the prototype variables. Otherwise, modifying the property of an object in one place would modify the same property for all objects which belong to that prototyping chain. – Chris Hayes Sep 16 '13 at 05:36
  • 1
    this is how javascript is designed..best solution would be create new `obj.bar="b"` and then use it..proto wont change in this case. – HIRA THAKUR Sep 16 '13 at 05:37
  • @meagar no u are wrong – Maizere Sep 16 '13 at 05:38
  • 2
    @Maizere Can you clarify? "u are wrong" is not an effective argument. – user229044 Sep 16 '13 at 05:38
  • @Maizere "no u are wrong" is not a conversation or useful discussion. If you have actual points, explain and support them. – Chris Hayes Sep 16 '13 at 05:39
  • @Maizere:he is correct!!! – HIRA THAKUR Sep 16 '13 at 05:39
  • @meagar if there is a setter function somewhere in prototype chain wont that be invoked with assignment???So how can u say that there is no prototype involved – Maizere Sep 16 '13 at 06:23
  • @Maizere No, there is no syntactic sugar that allows `y.name = "pathak"` to invoke a "setter function". If you'd written `y.setName("pathak")`, then yes, the prototype would be involved. But simple assignment is *not* equivalent to invoking a setter. – user229044 Sep 16 '13 at 11:51
  • @meagar check urself,if there is a setter with the name "name" ,than it gets invoked – Maizere Oct 06 '13 at 20:22
  • If you've actually defined a setter, then yes, the setter is invoked. This isn't related to your question, where there is no setter defined; assigning may invoke a setter, but it *still* isn't equivalent to writing to the object's prototype. – user229044 Oct 06 '13 at 20:26

0 Answers0