【问题标题】:How do I wrap a constructor?如何包装构造函数?
【发布时间】:2012-04-23 11:54:59
【问题描述】:

我有这个 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();

assertEquals(1, t.extraField);

[编辑]我想要一个实例属性,而不是类(静态/共享)属性。

包装函数中执行的代码应该像我将其粘贴到真正的构造函数中一样工作。

Type 的类型不应改变。

【问题讨论】:

  • 据我了解,您想在构造函数中添加一个附加属性吗?以便进一步的新实例具有该属性?
  • 您可能只需要在wrap() 函数中更改Type 的原型。例如:var wrap = function(cls) { cls.prototype.extraField=1; };?或者最好创建新的Type2 继承自Type 并添加额外的extraField 成员?
  • 您能更详细地描述您的问题吗?
  • 我想要一个实例属性,而不是类(静态/共享)属性。在包装函数中执行的代码应该像我将其粘贴到真正的构造函数中一样工作。

标签: javascript oop constructor


【解决方案1】:

更新:An updated version here

您实际上正在寻找的是将 Type 扩展到另一个类。在 JavaScript 中有很多方法可以做到这一点。我不太喜欢 newprototype 构建“类”的方法(我更喜欢寄生继承风格),但我得到了以下结果:

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

【讨论】:

  • 从您的控制台输出中,我想扩展存储在constructor 中的函数。新字段应显示在 name 旁边,而不是 constructor 旁边。
  • 所以你真正想做的是创建另一个构造函数?还是只是添加到现有的?
  • 我想扩展现有的构造函数。
  • 而不是cls.prototype.constructor.call(this, name),我会使用cls.call(this, name)。相同的功能,如果.constructor 属性确实存在,则无需担心。 foo.prototype = new cls(); 的危险在于 cls 可能是一个需要参数的函数。这就是首选foo.prototype = Object.create(cls.prototype) 的地方。
  • this example 显示经典修复。它只模拟Object.create 的“使用原型创建对象”部分,但这就是您所需要的。
猜你喜欢
  • 2018-12-13
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多