简体   繁体   English

我如何包装构造函数?

[英]How do I wrap a constructor?

I have this JavaScript:我有这个 JavaScript:

var Type = function(name) {
    this.name = name;
};

var t = new Type();

Now I want to add this:现在我想添加这个:

var wrap = function(cls) {
    // ... wrap constructor of Type ...
    this.extraField = 1;
};

So I can do:所以我可以这样做:

wrap(Type);
var t = new Type();

assertEquals(1, t.extraField);

[EDIT] I'd like an instance property, not a class (static/shared) property. [编辑]我想要一个实例属性,而不是 class(静态/共享)属性。

The code executed in the wrapper function should work as if I had pasted it into the real constructor.在包装器 function 中执行的代码应该像我将其粘贴到真正的构造函数中一样工作。

The type of Type should not change. Type 的Type不应该改变。

update: An updated version here更新:此处更新版本

what you were actually looking for was extending Type into another Class. There are a lot of ways to do that in JavaScript. I'm not really a fan of the new and the prototype methods of building "classes" (I prefer the parasitic inheritance style better), but here's what I got:您实际上正在寻找的是将 Type 扩展到另一个 Class。在 JavaScript 中有很多方法可以做到这一点。我并不是真正喜欢构建“类”的new方法和prototype方法(我更喜欢寄生 inheritance风格更好),但这是我得到的:

//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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM