2011-09-17 39 views
0

我想检查我的代码中的特定类型的对象。即使对象在其原型中具有构造函数,但仍然无法返回正确的对象类型,并且在使用instanceof运算符时始终返回“object”。为什么instanceof使用带参数的构造函数为单例返回false?

这里是对象的示例:

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 + "]"); 
     } 
    } 
}); 

回答

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 
+0

谢谢,我明白现在发生了什么。我假设返回的对象字面量被分配为Simple的原型。 – DoryuX

相关问题