Как мне обернуть конструктор?

У меня есть этот 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);

[EDIT] Я хотел бы свойство экземпляра, а не свойство класса (статические / общие).

Код, выполняемый в функции-обертке, должен работать так, как будто я вставил его в настоящий конструктор.

Тип Type не должно меняться.

1 ответ

Решение

Обновление: обновленная версия здесь

на самом деле вы искали расширение Type в другой класс. Есть много способов сделать это в JavaScript. Я на самом деле не фанат new и prototype методы построения "классов" (я предпочитаю стиль паразитического наследования), но вот что я получил:

//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);
Другие вопросы по тегам