Javascript [this] keyword binding with new -


this question has answer here:

when reading book you don't know js: & object prototypes

i found example this binding:

function foo(something) {   this.a = something; }  var obj1 = {  foo: foo };  var obj2 = {};  obj1.foo( 2 ); console.log( obj1.a ); // 2  obj1.foo.call( obj2, 3 ); console.log( obj2.a ); // 3  var bar = new obj1.foo( 4 ); console.log( obj1.a ); // 2 console.log( bar.a ); // 4 

i don't understand why after execution of new obj1.foo(4) console.log(obj1.a) prints 2 , not 4. , if comment line obj1.foo(2) result of log above undefined.

because function can constructor. imagine if used foo itself:

var obj3 = new foo(3); 

you'd expect object similar { a: 3 }, right?

this still works if function attached else. every time use new you're creating new object, not changing existing one.

in first instance, you're using function method:

obj1.foo(2); 

in case, context set obj1 since it's 1 invoked it. when use new brand new object created , new object used context.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

dataset - MPAndroidchart returning no chart Data available -

post - imageshack API cURL -