javascript - Why can't set the value type property of prototype via the this pointer -


i have following javascipt code.

var person = function(){}; person.prototype.age = 0; person.prototype.setage = function(age) {     this.age = age; };  var jack = new person(); console.log(jack.age); // #1 jack.setage(25);  // why not function assign value person.prototype.age. console.log(jack.age); // #2 console.log(jack); 

after running code, got output below.

0 25 person {age: 25, age: 0, setage: function} age: 25 __proto__: object     age: 0     constructor: function (){}     setage: function (age) {     __proto__: object 

at statement labeled #1, age property found in prototype of jack instance. reasonable print 0.

at statement jack.setage(25);, when execute code this.age = age;, seems new property added jack instance. i'm confused why not function jack.setage(25); assign value person.prototype.age?

thanks,

jeffrey

what happens is:

  1. intepreter looks setage function in jack object.
  2. it's not there, looks 1 level in prototype chain. it's there.
  3. intepreter invokes setage jack bound this. this.age in setage relates jack, not jack.prototype. jack.age = 25.

if want modify age property of person, can call:

 person.prototype.setage(7); 

(now this bound person.prototype).


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -