-
-
Save petermichaux/2489714 to your computer and use it in GitHub Desktop.
Function.prototype.new = function() { | |
var obj = Object.create(this.prototype); | |
this.apply(obj, arguments); | |
return obj; | |
}; | |
function Person(name) { | |
this.setName(name); | |
} | |
Person.prototype.getName = function() { | |
return this.name; | |
}; | |
Person.prototype.setName = function(name) { | |
this.name = name; | |
}; | |
var david = Person.new('Dave'); | |
david.getName(); // 'Dave' |
You have 2 big issues. Both are related with the built-in constructors and Object.create. Even and every object inherits from Object.prototype, the objects have hidden internal behavior which depends on the type of the objects. e.g arrays have special setter, functions have call and construct methods etc.
Array.new();
Will create a new native object which inherits from Array.prototype but it would not be true array, because the internal behavior is not inherited trough the prototype chain.
The second problem is again with built-ins which have non-generic methods, e.g.:
String(String.new('')); // TypeError: String.prototype.toString is not generic
A better way to implement new
is as follows: https://gist.github.com/aaditmshah/6269739
See the following StackOverflow answer: http://stackoverflow.com/a/17345713/783743
@petermichaux I'm not sure what you want to point now.
What's clear to me from any version of this benchmark is that using
new
is magnitudes faster than native or shimmedObject.create
version. Exception is just Firefox on which it's pretty same, hopefully Chrome and Safari will have it fixed, at least I don't see any technical reason why it should be so slow there.