[英]more wacky JavaScript shenanigans coming to mind
我刚刚阅读了Mike Koss的JavaScript面向对象编程 。 他简要地讨论了子分类,并谈到了“另一种子分类范例”。 在此示例之后,Koss写道...
不幸的是,该技术不允许使用
instanceof
运算符来测试超类的成员资格。 但是,我们具有可以从多个超类(多重继承)中派生的附加好处。
...这让我开始思考。 多重继承的想法似乎很酷! 所以我有两套问题:
instanceof
运算符,以将其功能扩展到多重继承? 在JavaScript中模拟多重继承成为噩梦。
我编写了一个完整的自定义类包装程序,以允许动态多重继承,一个月后就放弃了它,因为这样做不值得。 复杂性变得一发不可收拾。
而不是使用多重继承,而是可以使用其父方法扩展对象。
我建议您坚持使用简单的对象构造函数和原型,而不要包括外部“经典OO”仿真器。 JavaScript非常关注原型OO,它是从另一个对象继承的对象,而不是扩展另一个类的类。
如果要多重继承,则坚持对象组合。
警告:为了简洁起见,它使用_
。
function Child() {
var parent1 = new Parent1();
var parent2 = new Parent2();
// bind this to parent1 so it's got it's own internal scope
_.bindAll(parent1);
_.bindAll(parent2);
// extend this with parent1 and parent2
_.extend(this, parent1);
_.extend(this, parent2);
}
是的,您会丢失instanceof
检查。 处理它。
通常,您可以扩展所需的任何对象。
function extend(f, arr) {
// return a new function to replace f.
return function() {
// store the correct this value
var that = this;
// call original f
f.apply(this, arguments);
// for each parent call it with the original this
_.each(arr, function(v) {
v.apply(that, arguments);
});
// add f to the parent array
arr.push(f);
// store the array on the object to use with instance_of
this.__instance = arr;
}
}
function instance_of(o, klass) {
// is the klass included in the .__instance array ?
return _.include(o.__instance, klass);
}
function Child() {
// do stuff
this.method = function() { console.log("method"); return this;};
}
function Parent1() {
this.foo = function() { console.log("foo"); return this; };
}
function Parent2() {
this.bar = function() { console.log("bar"); return this;};
}
Child = extend(Child, [Parent1, Parent2]);
var c = new Child();
console.log(instance_of(c, Parent1)); // true
console.dir(c);
c.method().foo().bar();
这确实依靠underscore.js
来实现一些不错的抽象,以使示例代码保持较小。 .extend , .bindAll 。
查看现场示例
约翰·雷西格(John Resig)的班级结构以及许多其他课程都允许进行instanceof检查。
您并没有想到要重写instanceof(我实际上是为您的想法而赞扬,这是我会做的事情:)),但那是不可能的。 instanceof不是函数,它是由编译器解析的javascript关键字,因此无法覆盖。
至于多重继承,在实践中没有人使用它,因为无法跟踪。 当两个父类实现同一件事时会发生什么? 哪个优先? 您如何将它们与孩子班级区分开?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.