Skip to content

Instantly share code, notes, and snippets.

@sja
Created December 15, 2013 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sja/7977504 to your computer and use it in GitHub Desktop.
Save sja/7977504 to your computer and use it in GitHub Desktop.
Wie 'new' und 'strict mode' zusammenhängen.
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