Skip to content

Instantly share code, notes, and snippets.

@fabiomcosta
Created May 30, 2011 01:48
Show Gist options
  • Save fabiomcosta/998347 to your computer and use it in GitHub Desktop.
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
/*
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');
@fabiomcosta
Copy link
Author

a jsbin to change it or see it working http://jsbin.com/apule5/edit

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