简体   繁体   English

javascript中的instanceof运算符令人困惑的行为

[英]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
  1. Why is foo not an instance of Foo ? 为什么foo不是Foo的实例?
  2. Why is this an instance of Foo ? 为什么thisFoo的实例?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM