Skip to content

Instantly share code, notes, and snippets.

@gerardpaapu
Created May 16, 2012 05:53
Show Gist options
  • Save gerardpaapu/2707859 to your computer and use it in GitHub Desktop.
Save gerardpaapu/2707859 to your computer and use it in GitHub Desktop.
'new' keyword and Object.create
// nuevo(Klass, [arg, ...]) is roughly the same as
// new Klass(arg, ...)
//
// This should (hopefully) illustrate the relationship between
// Object.create and 'new'
//
// new Constructor ties together
// - creating an instance of the prototype
// - initializing it
// - possibly returning a totally different value
//
// Object.create(obj) does only the first, and guaruntees
// that obj.isPrototypeOf(Object.create(obj))
function nuevo(Constructor, args) {
// clone the prototype
var instance = Object.create(Constructor.prototype);
// Run the constructor
var result = Constructor.apply(instance, args);
// if the constructor returns a value,
// return that value
// otherwise return the instance
return result != null ? result : instance;
}
// As a counter point, Object.create can be defined (again roughly) in
// terms of the 'new' keyword
function create(obj) {
var F = function () {};
F.prototype = obj;
return new F();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment