如何包装构造函数? [英] How do I wrap a constructor?

查看:124
本文介绍了如何包装构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个JavaScript:

I have this 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);

我想要一个实例属性, (静态/共享)属性。

I'd like an instance property, not a class (static/shared) property.

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

The code executed in the wrapper function should work as if I had pasted it into the real constructor.

类型的类型不应该更改。

推荐答案

更新:此处有更新版本

你实际寻找的是将Type扩展到另一个类。在JavaScript中有很多方法可以做到这一点。我不是真正的原型建立类的方法(我更喜欢寄生继承风格更好),但这里是我得到:

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:

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

这篇关于如何包装构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆