用原型扩展基本实例?

时间:2013-03-26 07:17:20

标签: javascript prototypal-inheritance

这就是情况;我有一个名为Car的基类(函数)和一些特定的子类,如truckbuspartybus

我的脚本允许用户创建一个car,稍后由服务器更新该汽车的确切随机性(不可能预测它将是什么)。那时我已经拥有car的实例,其中包含所有者/ milage信息,但需要使用truck扩展已创建的实例,以便覆盖方法getTopSpeed并覆盖carInstance变为myExtendedInstance instanceof truck===true

创建基类和子类函数/扩展不是问题。这是代码;

function Car(){
}
Car.prototype.getTopSpeed=function(){
    return 100;
}

function Truck(){
    Truck.uber.constructor.call(this);
}
Truck.prototype.getTopSpeed=function(){
    return 20;
}
inherit.call(this, Truck, Car);
继续Dustin Diaz / Ross Harmes的继承功能

inherit=function _inherit(subClass, superClass){
    var F=function(){};
    F.prototype=superClass.prototype;
    subClass.prototype=new F();
    subClass.prototype.constructor=subClass;

    subClass.uber=superClass.prototype;
    if (superClass.prototype.constructor===Object.prototype.constructor){
        superClass.prototype.constructor=superClass;
    }
}

问题是如何从一个已创建的baseClass实例到一个工作子类,并最佳地返回到baseClass和另一个子类,而不需要创建一个新的子类实例并销毁它baseClass的实例。

我可以致电myExtendedInstance=inherit(carInstance, Truck)吗?这不会造成内存泄漏或模糊我的原型链吗?如果没有,我怎样才能再次破坏原型链返回基本的carInstance?

我想我的脑袋里有一个结。任何帮助将非常感激! :)

3 个答案:

答案 0 :(得分:1)

你可以让它工作,但我认为这种方法(改变一个对象的类)很复杂。

我会创建一个Car类和另一个类CarSettings或类似的东西。

每个Car对象都将包含一个CarSettings对象,可以对其进行修改或替换。

答案 1 :(得分:1)

我看到像这样的继承助手的问题是

使用new创建继承的类并在没有的情况下调用constructor 参数subClass.prototype=new F(); 在继承过程中,如果构造函数依赖于特定的参数,那么(在我看来)可以轻松地打破更复杂的构造函数。

所以为了解决这个问题并且能够做你的问题,我目前使用的是这样的东西:

抱歉,我误解了最初的问题并修改了帮助我使用了一点点来支持扩展和缩减。

var base = (function baseConstructor() {
    var obj = {
        create: function instantiation(extend) {
            var instance, args = [].slice.call(arguments);
            if (this === base) {
                throw new SyntaxError("You can't create instances of base");
            } else if (!this.hasOwnProperty("initclosure")) {
                throw new SyntaxError("Cannot create instances without an constructor");
            } else if (this.singleton && this.instances.length !== 0) {
                throw new SyntaxError("You can't create more than one Instance of a Singleton Class");
            } else {
                if (!extend._class || !extend._class.isPrototypeOf(this)) {
                    instance = Object.create(this.pub);
                    this.instances.push(instance);
                } else {
                    args = args.slice(1);
                    extend._class.remove(extend);
                    instance = this.extend(extend);
                }
                this.init.apply(instance, args);
                instance.onCreate();
                return instance;
            }
        },
        extend: function (instance) {
            if (!instance._class.isPrototypeOf(this)) {
                return;
            }
            var extended = Object.create(this.pub);
            for (var propInst in instance) {
                if (instance.hasOwnProperty(propInst)) {
                    extended[propInst] = instance[propInst];
                }
            }
            instance._class.remove(instance);
            this.instances.push(extended);
            return extended;
        },
        reduce: function (instance) {
            if (!instance.instanceOf(this)) {
                return;
            }
            var reduced = Object.create(this.pub);
            for (var propRed in instance) {
                if (instance.hasOwnProperty(propRed)) {
                    reduced[propRed] = instance[propRed];
                }
            }
            instance._class.remove(instance);
            this.instances.push(reduced);
            return reduced;
        },
        remove: function (instance) {
            if (instance.instanceOf(this)) {
                var removed = this.instances.splice(this.instances.indexOf(instance), 1)[0];
                instance.onRemove();
                return removed;
            }
        },
        inherit: function inheritation(specsOpt) {
            specsOpt = specsOpt || {};
            applyDefaults(specsOpt, {
                singleton: false,
                anonymous: false
            });
            var sub = Object.create(this);
            sub.pub = Object.create(this.pub);
            sub.pub.proto = this.pub;
            sub.pub._class = sub;
            sub.instances = [];
            sub.anonymous = specsOpt.anonymous;
            sub.sup = this;
            if (specsOpt.singleton) {
                sub.singleton = specsOpt.singleton;
                sub.getSingleton = getSingleton;
                protect.call(sub, {
                    singleton: {
                        writable: false,
                        configurable: false,
                        enumerable: false
                    },
                    getSingleton: {
                        writable: false,
                        configurable: false
                    }
                });
            }
            return sub;
        },
        initclosure: function Base() {},
        instances: [],
        pub: {
            instanceOf: function (obj) {
                if (!obj || !obj.pub) {
                    return this.className;
                }
                return obj.pub.isPrototypeOf(this);
            },
            onRemove: function () {},
            onCreate: function () {},
            "_class": obj
        }
    };
    /* Helper Functions. --- Use function expressions instead of declarations to get JSHint/Lint strict mode violations
     *
     * TODO: Maybe add an obj.helper Propertie with usefull functions
     */
    var applyDefaults = function (target, obj) {
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                target[prop] = target[prop] || obj[prop];
            }
        }
    };
    var getSingleton = function () { //To get past the strict violation
        return this.instances[0];
    };
    var protect = function (props, desc) { //Maybe change it a little
        for (var prop in props) {
            if (props.hasOwnProperty) {
                Object.defineProperty(this, prop, props[prop] || desc);
            }
        }
        return this;
    };
    /*  End Helpers
     * 
     *  Protecting
     */
    Object.defineProperty(obj, "init", {
        set: function (fn) {
            if (typeof fn !== "function") {
                throw new Error("Expected typeof init to be 'function'");
            } else if (Boolean(fn.name) === this.anonymous) {
                try {
                    throw new Error("Expected the constructor " + (!this.anonymous ? "not " : "") + "to be Anonymous");
                } catch (e) {
                    console.error(e.stack);
                }
            }
            if (!this.hasOwnProperty("initclosure")) {
                this.initclosure = fn;
                this.pub.constructor = this.init;
                this.pub.className = fn.name;
                protect.call(this.pub, {
                    constructor: false,
                    className: false
                }, {
                    enumerable: false
                });
            }
        },
        get: function () {
            var that = this;
            var init = function init() {
                if (that.pub.isPrototypeOf(this)) {
                    that.initclosure.apply(this, arguments);
                } else {
                    throw new Error("init can't be called directly");
                }
            };
            init.toString = function () {
                return that.initclosure.toString();
            };
            return init;
        }
    });
    obj.toString = function () {
        return "[class " + (this.initclosure.name || "Class") + "]";
    };
    obj.pub.toString = function () {
        return "[instance " + (this.className || "Anonymous") + "]";
    };
    protect.call(obj, {
        create: false,
        inherit: false,
        toString: false,
        onRemove: {
            enumerable: false
        },
        onCreate: {
            enumerable: false
        },
        initclosure: {
            enumerable: false
        }
    }, {
        writable: false,
        configurable: false
    });
    protect.call(obj.pub, {
        instanceOf: false,
        toString: false,
        "_class": {
            enumerable: false
        }
    }, {
        writable: false,
        configurable: false,
        enumerable: false
    });
    return obj;
})();

注意:这取决于ECMAScript 5中引入的Object.create,因此旧浏览器不支持


鉴于继承助手,我们可以创建一些“类”

var Car = base.inherit();
Car.pub.getTopSpeed = function () {
    return 100;
};
Car.init = function ClassCar(model) {
    this.model = model || this.model || "";
};
Car.pub.type = "car";

现在我们有了一个可继承的超类,让Truck继承自Car

var Truck = Car.inherit();
Truck.pub.getTopSpeed = function () {
    return 20;
};
Truck.pub.type = "truck";
Truck.init = function ClassTruck(model, color) {
    Truck.sup.init.apply(this, [].slice.call(arguments));
    this.color = color;
};

然后我们创建一个Car

的实例
var myCar = Car.create("Porsche");
console.log(myCar.getTopSpeed(), myCar.className); //100, ClassCar

现在,如果我理解正确,您希望将myCar的现有实例Car扩展为Truck的实例。
如果是这样,让我们​​这样做

var myExtendedTruck = Truck.extend(myCar);
console.log(myExtendedTruck.getTopSpeed(), myExtendedTruck.className); //20, ClassTruck
console.log(myExtendedTruck.instanceOf(Truck)); //true

这只是将扩展原型链copys实例变量设置为新的Truck实例。因此,Car实例现在是Truck实例

或者如果你也想使用构造函数。 在传递超类的实例时,create也可以正常工作 然后它被扩展并初始化。

var myConstructedExtendedTruck = Truck.create(myCar, myCar.model, "Yellow");
console.log(myConstructedExtendedTruck.getTopSpeed(), myConstructedExtendedTruck.model, myConstructedExtendedTruck.color); //20 , Porsche , Yellow

现在我们有一个扩展Car实例,它现在是Truck的实例,并由Trucks构造函数正确构造。

现在,如果我做对了,你也希望能够回到超类Instance。

var myReducedCar = Car.reduce(myExtendedTruck);
console.log(myReducedCar.getTopSpeed(), myReducedCar.className); //100, ClassCar
console.log(myReducedCar.instanceOf(Truck)); //false

继承人Example on JSBin来摆弄一下

编辑注释:修复了在类instances数组中正确移动实例的代码

答案 2 :(得分:1)

  

我可以致电myExtendedInstance=inherit(carInstance, Truck)吗?这不会造成内存泄漏或模糊我的原型链吗?

没有。它不会造成内存泄漏,但inherit只需要构造函数(类)作为参数而不是实例。

  

如果没有,我怎样才能再次破坏原型链返回基本的carInstance?

您无法修改现有对象的原型链 - 除非您使用非标准__proto__ property(例如,IE不支持)。

相反,您需要创建myExtendedInstance = new Truck;,然后复制旧版carInstance的所有者/ milage属性。