Last active
August 29, 2015 14:17
-
-
Save muffinresearch/f056dd4698b4a908b141 to your computer and use it in GitHub Desktop.
Using arguments in flexible constructor
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
function MyConstructor(foo, bar){ | |
if (!(this instanceof MyConstructor)){ | |
var obj = Object.create(MyConstructor.prototype); | |
return MyConstructor.apply(obj, arguments); | |
} | |
this.foo = foo; | |
this.bar = bar; | |
return this; | |
} | |
var instance1 = MyConstructor('foo1', 'bar1'); | |
var instance2 = new MyConstructor('foo2', 'bar2'); | |
console.log([instance1.foo, instance1.bar]); | |
console.log([instance2.foo, instance2.bar]); | |
instance1.foo = 'whatever'; | |
console.log([instance1.foo, instance1.bar]); | |
console.log([instance2.foo, instance2.bar]); | |
console.log(instance1 instanceof MyConstructor); | |
console.log(instance2 instanceof MyConstructor); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment