Created
December 15, 2013 20:09
-
-
Save sja/7977504 to your computer and use it in GitHub Desktop.
Wie 'new' und 'strict mode' zusammenhängen.
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
console.clear(); | |
/* | |
In both functions below, MyObj has the same declaration, but if they're called as strict or non-strict depends on the place where it's defined. | |
*/ | |
(function() { | |
console.log("Without strict mode:"); | |
var MyObj = function (name) { | |
console.log("myScope for ", name, ":", this); | |
}; | |
/* | |
This will print 'Unstrict: {top, window, location, ...}' | |
because no new Scope is created for the constructor. | |
Instead, the current scope is the document here. | |
Variable declarations in constructor will create | |
global variables. | |
*/ | |
MyObj("Unstrict"); | |
/* | |
This will print 'Unstrict with new: MyObj {}' | |
because a new Scope is created with the new keyword. | |
Actions in contructor won't modify the global scope. | |
*/ | |
new MyObj("Unstrict with new"); | |
})(); | |
(function() { | |
"use strict"; | |
console.log("With strict mode:"); | |
var MyObj = function (name) { | |
console.log("myScope for ", name, ":", this); | |
}; | |
/* | |
This will print 'Strict: undefined' | |
because no new Scope is created for the constructor and | |
it would ne unsafe to pass in the global object. | |
*/ | |
MyObj("Strict"); | |
/* | |
In strict mode, this is the only correct way to create a | |
new object. It will print 'Strict with new: MyObj {}'. | |
*/ | |
new MyObj("Strict with new"); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment