Javascript [this] keyword binding with new -
this question has answer here:
- what 'new' keyword in javascript? 11 answers
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
Post a Comment