Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Created February 16, 2012 19:58
Show Gist options
  • Save coolaj86/1847413 to your computer and use it in GitHub Desktop.
Save coolaj86/1847413 to your computer and use it in GitHub Desktop.
A new pattern (pun intended) - strict, non-strict mode, object.create
// 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
}());
@statianzo
Copy link

Just a note, Foo.create doesn't pass arguments to new Foo() or return anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment