[英]confusing behavior of instanceof operator in javascript
Take a look at this code: 看一下这段代码:
function Foo () {
console.log(this instanceof Foo);
return { name: "nitesh" };
}
foo = new Foo(); //true
console.log(foo instanceof Foo) //false
foo
not an instance of Foo
? 为什么foo
不是Foo
的实例? this
an instance of Foo
? 为什么this
是Foo
的实例? In your Foo
function, you are returning an object. 在Foo
函数中,您将返回一个对象。 This is what foo
gets set to. 这就是foo
的设置。 That is not a Foo
object, it's just a "normal" object. 那不是Foo
对象,而只是一个“普通”对象。
Try it this way: 尝试这种方式:
function Foo(){
console.log(this instanceof Foo);
this.name = "nitesh";
}
var foo = new Foo(); //true
console.log(foo instanceof Foo) //true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.