Created
August 2, 2013 09:20
-
-
Save tobiashm/6138588 to your computer and use it in GitHub Desktop.
Helper function to ensure correct context in JavaScript constructor.
Alternative to `function Foo(...) { if (!(this instanceof Foo)) return new Foo(...); ... }`
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.prototype.make = function(self, args) { | |
if (self instanceof args.callee) return self; | |
var F = function() {}; | |
F.prototype = args.callee.prototype; | |
var o = new F(); | |
F.prototype.constructor.apply(o, Array.prototype.slice.apply(args)); | |
return o; | |
}; | |
function Foo(name) { | |
var foo = Foo.make(this, arguments); | |
foo.name = name; | |
return foo; | |
} | |
var bar = new Foo('john'); | |
var baz = Foo('paul'); | |
console.log('bar is Foo => ' + (bar instanceof Foo)); | |
console.log('baz is Foo => ' + (baz instanceof Foo)); | |
console.log('bar.name => ' + bar.name); | |
console.log('baz.name => ' + baz.name); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment