Why does instanceof return false for a singleton using a constructor with arguments?
I'm trying to check for a specific type of object in my code. Even though the object has the constructor in its prototype, it is still failing to return the correct object type and always returns with "object" when using the instanceof operator.
Here's an example of the 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: " + 开发者_如何学Python_w);
console.log("xyz: [" + this.x + ", " + this.y + ", " + this.z + "]");
}
}
});
You're returning an object literal with the constructor
property to set to the function Simple
. The internal constructor is still set to Object
, so instanceof
returns false.
For instanceof
to return true, you need to set properties using this.property
in the constructor or use prototypes, and initalize a new object using 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
精彩评论