【问题标题】:Why does instanceof return false for a singleton using a constructor with arguments?为什么 instanceof 使用带参数的构造函数为单例返回 false?
【发布时间】:2011-09-17 23:56:42
【问题描述】:

我正在尝试在我的代码中检查特定类型的对象。即使对象的原型中有构造函数,它仍然无法返回正确的对象类型,并且在使用 instanceof 运算符时总是返回“object”。

这是一个对象的例子:

Simple = (function(x, y, z) {
    var _w = 0.0;

    return {
        constructor: Simple,

        x: x || 0.0,
        y: y || 0.0,
        z: z || 0.0,

        Test: function () {
            this.x += 1.0;
            this.y += 1.0;
            this.z += 1.0;

            console.log("Private: " + _w);
            console.log("xyz: [" + this.x + ", " + this.y + ", " + this.z + "]");
        }
    }
});

【问题讨论】:

    标签: javascript constructor singleton instanceof


    【解决方案1】:

    您将返回一个带有 constructor 属性的对象文字,以设置为函数 Simple。内部构造函数仍然设置为Object,所以instanceof 返回false。
    要让instanceof返回true,你需要在构造函数中使用this.property设置属性或者使用原型,并使用new Simple()初始化一个新对象。

    function Simple(x, y, z) {
        var _w = 0.0;
    
        this.x = x || 0.0;
        this.y = y || 0.0;
        this.z = z || 0.0;
    
        this.Test = function () {
                this.x += 1.0;
                this.y += 1.0;
                this.z += 1.0;
    
                console.log("Private: " + _w);
                console.log("xyz: [" + this.x + ", " + this.y + ", " + this.z + "]");
            }
      });
      (new Simple()) instanceof Simple //true
    

    【讨论】:

    • 谢谢,我知道现在发生了什么。我假设返回的对象字面量被分配为 Simple 的原型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    相关资源
    最近更新 更多