我看到这样的继承助手的问题是
继承的类是使用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;
})();
注意:这依赖Object.create
于 ECMAScript 5 中引入的内容,因此旧版浏览器不支持
给定继承帮助器,让我们创建一些“类”
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
现在,如果我对您的理解正确,您希望将现有的 Instance扩展myCar
为. 如果是这样,让我们这样做Car
Truck
var myExtendedTruck = Truck.extend(myCar);
console.log(myExtendedTruck.getTopSpeed(), myExtendedTruck.className); //20, ClassTruck
console.log(myExtendedTruck.instanceOf(Truck)); //true
这只是设置扩展原型链将实例变量复制到新的卡车实例。所以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
构造。
现在,如果我做对了,您也希望能够回到超类实例。
var myReducedCar = Car.reduce(myExtendedTruck);
console.log(myReducedCar.getTopSpeed(), myReducedCar.className); //100, ClassCar
console.log(myReducedCar.instanceOf(Truck)); //false
这是一个关于 JSBin的示例,可以稍微摆弄一下
编辑说明:修复代码以正确移动 Classesinstances
数组中的实例