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:
- intepreter looks
setage
function injack
object. - it's not there, looks 1 level in prototype chain. it's there.
- intepreter invokes
setage
jack
bound this.this.age
insetage
relatesjack
, notjack.prototype
. jack.age = 25.
if want modify age
property of person, can call:
person.prototype.setage(7);
(now this
bound person.prototype
).
Comments
Post a Comment