在 JavaScript 中,有一种实现继承的模式,称为“函数式继承”,在 Crockfords“JavaScript:优秀部分”的第 5 章中进行了描述。
与使用伪经典模式相比,该模式的缺点之一是我们失去了使用 instanceof
运算符区分类型的能力。
有什么方法可以达到同样的目标吗?我们如何知道两个对象在某种程度上相关,因为它们具有相同的父/基“类型”?
此外,即使它们是同一类型的后代,我们又如何辨别它们本身是不同的类型?
我不知道不能使用 instanceof
是否是一个很大的损失,但看起来并非如此。
注释
最佳答案
instanceof
运算符并不特殊。您可以按照 Mozilla Developer Network 上的说明自行实现它。 。有关更多详细信息,请参阅以下问题的已接受答案:
JavaScript inheritance and the constructor property
以下是如何在 JavaScript 中实现 instanceof
运算符:
function instanceOf(object, constructor) {
while (object != null) {
if (object == constructor.prototype) { //object is instanceof constructor
return true;
} else if (typeof object == 'xml') { //workaround for XML objects
return constructor.prototype == XML.prototype;
}
object = object.__proto__; //traverse the prototype chain
}
return false; //object is not instanceof constructor
}
想要实现 instanceOf
来实现函数继承吗?这也很容易做到:
var object = child({ name: "a functional object" });
alert(object.instanceOf(child)); // true
alert(object.instanceOf(base)); // true
alert(object.sayHello()); // Hello, I'm a functional object
function base(spec) {
var that = {};
that.name = spec.name;
that.constructors = [base];
that.instanceOf = instanceOf;
return that;
}
function child(spec) {
var that = base(spec);
that.sayHello = sayHello;
that.constructors.push(child);
return that;
function sayHello() {
return "Hello, I'm " + this.name;
}
}
function instanceOf(constructor) {
return this.constructors.indexOf(constructor) >= 0;
}
当然,在真正的函数式编程中根本不需要使用instanceof
。
关于javascript - 使用函数继承时, `instanceof` 相当于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35395621/