Here is another one that has gotten me before, again ECMAScript 5 will take care of this mostly but until then it's tricky
given an object defined like this
var Obj = function(name) {
this.name=name;
};
What will the following do?
var o = new Obj('anewwin');
console.log(o.name);
As guessed, it will print 'anewwin' to the console
How about this?
var o = Obj('anewwin'); // No 'new' this time
console.log(o.name);
This time you get an error saying o.name does not exist. Why? Because Javascript interpreted 'this' inside the function as the global 'window' object instead. To prove this, add the following:
console.log(window.name); // This prints 'anewwin'
So, behind the scenes, in the absence of 'new', javascript is assigning 'this' to the global window object, thus causing confusion. ECMAScript 5 is supposed to stop assigning 'this' to the global object, for everyone's good.
Until then, the recommended fix is to never call without new, or for safety, do the following
function Obj() {
if (!(this instanceof Obj) ) {
return new Obj(); // To protect against invocations not using new, bounces back to this constructor but with proper object syntax
}
// continue with rest...
}
This makes sure the constructor does not mistakenly use the global 'this' object.
Reference: "Javascript Patterns", Stoyan Stefanov
given an object defined like this
var Obj = function(name) {
this.name=name;
};
What will the following do?
var o = new Obj('anewwin');
console.log(o.name);
As guessed, it will print 'anewwin' to the console
How about this?
var o = Obj('anewwin'); // No 'new' this time
console.log(o.name);
This time you get an error saying o.name does not exist. Why? Because Javascript interpreted 'this' inside the function as the global 'window' object instead. To prove this, add the following:
console.log(window.name); // This prints 'anewwin'
So, behind the scenes, in the absence of 'new', javascript is assigning 'this' to the global window object, thus causing confusion. ECMAScript 5 is supposed to stop assigning 'this' to the global object, for everyone's good.
Until then, the recommended fix is to never call without new, or for safety, do the following
function Obj() {
if (!(this instanceof Obj) ) {
return new Obj(); // To protect against invocations not using new, bounces back to this constructor but with proper object syntax
}
// continue with rest...
}
This makes sure the constructor does not mistakenly use the global 'this' object.
Reference: "Javascript Patterns", Stoyan Stefanov
Comments
Post a Comment