Wednesday, 15 February 2012

javascript - "this" inside of a nested prototype not pointing to instance -



javascript - "this" inside of a nested prototype not pointing to instance -

this question has reply here:

prototype: deep scope of “this” access instance's scope 5 answers

given:

var x = function () { }; x.prototype = { y: { z: function () { console.log(this); } } }; var foo = new x(); foo.y.z();

why this logged in console y instead of x , how possible given y literal object without constructor?

"why logged in console y instead of x..."

because that's how javascript works. this value set object method invoked. should maintain objects off of .prototype. they're going shared among instances created using constructor.

"...and how possible given y literal object without constructor?"

it's easy. this value not tied constructor. it's dynamic value set based on how invoke function or method.

there utilities allow manually override natural value this set in invocation. using .call or .apply methods of function.prototype invoke method 1 example

var foo = new x(); foo.y.z.call(foo);

now this in z method foo object, because manually set passing first argument .call.

the .call method sees called method of z method, , invokes z you, sets this value of z whatever provided first argument... in case foo object.

but won't utilize objects values of .prototype. reason instances created constructor implicit reference .prototype of constructor, updates objects on properties of .prototype observed instances.

javascript

No comments:

Post a Comment