I wish to create a constructor of constructors. Relating to this thread : JavaScript build a constructor of constructors, it seems the only solutions are :
Function.prototype.add = function(name, value) {
this.prototype[name] = value;
};
Function.prototype.remove = function(name) {
delete this.prototype[name];
};
But I don't want to modify the generic Function
prototype... and also :
var A = new ConstBuilder().add('test', function() {
console.log('test');
}).getConstructor();
But I don't want to have an object wrapper around the constructor itself.
The problem is that generally constructors creates new objects, inheriting methods from the constructor prototype. What I'm trying to do is to instanciates functions instead of objects, but the only way to modify a function prototype property is this to modify its __proto__
property :
var constructorPrototype = {
add : function(name, value) {
this.prototype[name] = value ;
}
} ;
var ConstBuilder = function() {
var constructor = function() {} ;
constructor.prototype = {} ;
// The only way (?), but quite deprecated...
constructor.__proto__ = constructorPrototype ;
return constructor ;
} ;
// Not working way...
//ConstBuilder.prototype = constructorPrototype ;
var A = new ConstBuilder() ;
A.add('test', function() {
console.log('test') ;
}) ;
var a = new A() ;
a.test() ; // "test"
constructorPrototype.remove : function() {
delete this.prototype[name] ;
} ;
A.remove('test') ;
a.test() ; // Error: test is not a function.
Note that A.prototype
is not A.__proto__
but A.prototype
is (new A).__proto__
.
And it works perfectly by modifying __proto__
, what a shame.
I read that Firefox has integrated a "Object.setPrototypeOf()" but it is only experimental.
Would it be another way to do what I wish to do ?