Javascript 如何包装构造函数?
我有一个JavaScript:Javascript 如何包装构造函数?,javascript,oop,constructor,Javascript,Oop,Constructor,我有一个JavaScript: var Type = function(name) { this.name = name; }; var t = new Type(); 现在我想补充一点: var wrap = function(cls) { // ... wrap constructor of Type ... this.extraField = 1; }; 所以我可以做到: wrap(Type); var t = new Type(); assertEqual
var Type = function(name) {
this.name = name;
};
var t = new Type();
现在我想补充一点:
var wrap = function(cls) {
// ... wrap constructor of Type ...
this.extraField = 1;
};
所以我可以做到:
wrap(Type);
var t = new Type();
assertEquals(1, t.extraField);
[EDIT]我想要一个实例属性,而不是类(静态/共享)属性 在包装器函数中执行的代码应该像我将其粘贴到实际构造函数中一样工作
类型的类型不应更改。更新:
您实际上在寻找的是将类型扩展到另一个类中。在JavaScript中有很多方法可以做到这一点。我并不真正喜欢新的
和原型
构建“类”的方法(我更喜欢寄生继承风格),但我得到了以下几点:
//your original class
var Type = function(name) {
this.name = name;
};
//our extend function
var extend = function(cls) {
//which returns a constructor
function foo() {
//that calls the parent constructor with itself as scope
cls.apply(this, arguments)
//the additional field
this.extraField = 1;
}
//make the prototype an instance of the old class
foo.prototype = Object.create(cls.prototype);
return foo;
};
//so lets extend Type into newType
var newType = extend(Type);
//create an instance of newType and old Type
var t = new Type('bar');
var n = new newType('foo');
console.log(t);
console.log(t instanceof Type);
console.log(n);
console.log(n instanceof newType);
console.log(n instanceof Type);
据我所知,您想向构造函数添加一个附加属性吗?因此,进一步的新实例具有该属性?可能只需要在wrap()
函数中更改Type
的原型即可。例如:var wrap=function(cls){cls.prototype.extraField=1;}代码>?或者最好创建新的Type2
继承自Type
,并带有额外的extraField
成员?您能更详细地描述您的问题吗?我想要一个实例属性,而不是类(静态/共享)属性。包装函数中执行的代码应该像我将其粘贴到实际构造函数中一样工作。从控制台输出,我想扩展存储在构造函数中的函数。新字段应该显示在name
旁边,而不是constructor
旁边。因此,您真正想做的是创建另一个构造函数?或者只是添加到现有的?我想扩展现有的构造函数。而不是cls.prototype.constructor.call(this,name)
,我要做cls.call(this,name)
。相同的函数,如果.constructor
属性实际存在,则无需担心。foo.prototype=new cls()的危险
是指cls
可能是一个需要参数的函数。这就是首选foo.prototype=Object.create(cls.prototype)
的地方。显示了经典修复。它只模拟object.create
中的“使用原型创建对象”部分,但这就是这里需要的全部内容。