为什么对于使用带参数的构造函数的单例实例,instanceof 返回 false?
我正在尝试检查代码中是否存在特定类型的对象。即使对象的原型中有构造函数,它仍然无法返回正确的对象类型,并且在使用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 + "]");
}
}
});
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: " + _w);
console.log("xyz: [" + this.x + ", " + this.y + ", " + this.z + "]");
}
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将返回一个带有
constructor
属性的对象文字,以设置为函数Simple
。内部构造函数仍设置为Object
,因此instanceof
返回 false。要使
instanceof
返回 true,您需要在构造函数中使用this.property
设置属性或使用原型,并使用new Simple()< /代码>。
You're returning an object literal with the
constructor
property to set to the functionSimple
. The internal constructor is still set toObject
, soinstanceof
returns false.For
instanceof
to return true, you need to set properties usingthis.property
in the constructor or use prototypes, and initalize a new object usingnew Simple()
.