Sunday, September 11, 2016

JavaScript Safer 'this' in depth look

I am currently reading Kyle Simpson's series You Don't Know JavaScript (YDKJS) and I am learning a lot about JavaScript. I have been writing his code examples and other JavaScript blog code examples in my plunker. I decided to code out his warning for using a safer this.

var objNull = null;
var emptyObjLiteral = {};
// our DMZ(safe) empty object
var emptyObj = Object.create( null );

var objNull = null;
var emptyObjLiteral = {};
// our DMZ(safe) empty object
var emptyObj = Object.create( null );
Kyle mentioned that null could mutate or reference the global object in a function that makes a 'this' reference in either your own code or in a third party library.
function foo() {
console.log(this === window);//true
}
foo.call( null );

The empty object literal {} still has __proto__ since it inherited from 'Object'.

If you use a third party library or you have code that checks for properties on 'this' then you could have a difficult bug.

function foo() {<br/>
if (this['toString']) {<br/>
console.log('oops'); //this has .toString
}
}
foo.call( {} );
Object.create(null) truly is more empty than {}. It has no properties which makes it the safer 'this' option.



No comments:

Post a Comment