javascript - 使用函数继承时, `instanceof` 相当于什么?

标签 javascript inheritance functional-programming instanceof

在 JavaScript 中,有一种实现继承的模式,称为“函数式继承”,在 Crockfords“JavaScript:优秀部分”的第 5 章中进行了描述。

与使用伪经典模式相比,该模式的缺点之一是我们失去了使用 instanceof 运算符区分类型的能力。

有什么方法可以达到同样的目标吗?我们如何知道两个对象在某种程度上相关,因为它们具有相同的父/基“类型”?

此外,即使它们是同一类型的后代,我们又如何辨别它们本身是不同的类型?

我不知道不能使用 instanceof 是否是一个很大的损失,但看起来并非如此。

注释

对于那些不熟悉 Crockford 解释的人,您可以在以下位置查看示例:JSFiddle ,取自here .

最佳答案

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/

相关文章:

javascript - 新项目与本地 react 但错误

c# - 对待对象就像他们是 parent 一样

C++ 继承 - 从构造函数调用重写

python - map 与列表;为什么会有不同的行为?

javascript - IO 作为组合链中的第一个

javascript - 在闭包中保留变量内容时遇到问题

javascript - 从canvas元素获取SVG并保存

javascript - 如何在 CSS 或内联中增加 SVG 路径的宽度

Java:继承类不能在方法参数中转换为父类(super class)

javascript - 让 R.pipe 与 Promise 一起工作?