This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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