Created
February 16, 2012 19:58
-
-
Save coolaj86/1847413 to your computer and use it in GitHub Desktop.
A new pattern (pun intended) - strict, non-strict mode, object.create
This file contains hidden or 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
// Strict mode example | |
(function () { | |
"use strict"; | |
function Foo(a, b, c) { | |
if (!this) { | |
return new Foo(a, b, c); | |
} | |
this.a = a; | |
this.b = b; | |
this.c = c; | |
} | |
Foo.create = function (a, b, c) { | |
new Foo(a, b, c); | |
}; | |
Foo.create(1, 2, 3); // works | |
new Foo(1, 2, 3); // works | |
Foo(1, 2, 3); // works | |
}()); | |
// non-strict mode | |
(function () { | |
// http://stackoverflow.com/questions/3277182/how-to-get-the-global-object-in-javascript | |
var global = Function('return this;')(); | |
function Foo(a, b, c) { | |
if (global === this) { | |
return new Foo(a, b, c); | |
} | |
this.a = a; | |
this.b = b; | |
this.c = c; | |
} | |
Foo.create = function (a, b, c) { | |
new Foo(a, b, c); | |
}; | |
Foo.create(1, 2, 3); // works | |
new Foo(1, 2, 3); // works | |
Foo(1, 2, 3); // works | |
}()); | |
// Object.create | |
(function () { | |
"use strict"; | |
var foo | |
; | |
function Foo() { | |
} | |
foo = Object.create(Foo, { a: 'bar', b: 'baz', c: 'corge' }); | |
foo.a; // bar | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just a note,
Foo.create
doesn't pass arguments tonew Foo()
or return anything.