Created
May 16, 2012 05:53
-
-
Save gerardpaapu/2707859 to your computer and use it in GitHub Desktop.
'new' keyword and Object.create
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
| // 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