为什么使用带参数的构造函数的单例对象instanceof返回false ?

Why does instanceof return false for a singleton using a constructor with arguments?

本文关键字:对象 instanceof 返回 false 单例 构造函数 参数 为什么      更新时间:2023-09-26

我试图检查代码中特定类型的对象。即使对象的原型中有构造函数,它仍然不能返回正确的对象类型,并且在使用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 + "]");
        }
    }
});

您将返回具有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