Created
May 30, 2011 01:48
-
-
Save fabiomcosta/998347 to your computer and use it in GitHub Desktop.
niw - A way to create new object from a constructor without the 'new' operator, just for fun and to emulate how the new operator works on pure javascript. WARNING - DO NOT USE IT ON YOUR PROJECTS
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
/* | |
code snippet by Fabio Miranda Costa | |
Its just for the purpose of understanding how the 'new' operator works. | |
Should work on gecko and webkit. | |
WARNING - DO NOT USE IT ON YOUR PROJECTS | |
*/ | |
var niw = function(_constructor, args){ | |
var newObj = {'__proto__': _constructor.prototype}; | |
var ret = _constructor.apply(newObj, args); | |
return (typeof ret == 'object') ? ret : newObj; | |
}; | |
var Foo = function(){}; | |
Foo.prototype.foo = function(msg){ | |
console.log('foo', msg); | |
}; | |
var foo = niw(Foo); | |
foo.foo('foo'); | |
var Bar = function(){}; | |
Bar.prototype = niw(Foo); | |
Bar.prototype.constructor = Bar; | |
Bar.prototype.bar = function(msg){ | |
console.log('bar', msg); | |
}; | |
var bar = niw(Bar); | |
bar.bar('bar'); | |
bar.foo('bar'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a jsbin to change it or see it working http://jsbin.com/apule5/edit