将 object.constructor 与其构造函数和 instanceof 进行比较有什么区别?

What's thedifference between comparing object.constructor to its constructor and instanceof?

假设我有一个 Dog 构造函数

function Dog(name) {
    this.name = name;
}

我有一个构造函数的实例

const myDog = new Dog('Charlie');

据我最近了解到,有两种方法可以检查 myDog 是否是 Dog 的实例:

1.

console.log(myDog instanceof Dog) //true

2.

console.log(myDog.constructor === Dog) //true

我的问题是,两者有什么区别,哪个更好,为什么?

提前致谢。

区别很简单。查看 MDN's documentation of instanceOf。如果您有一个实例 Fido,它是 GreatDane 的实例,它又是 Dog 的实例,又是 Object 的实例,则情况如下:

Fido instanceof GreatDane // true
Fido instanceof Dog // true
Fido instanceof Object // true
Fido.constructor === GreatDane // true

但是,以下情况不会成立:

Fido.constructor === Dog // false
Fido.constructor === Object // false

因此您可以看到 instanceOf 关键字沿沿袭向上移动,其中 constructor 查看创建实例的实际函数。

哪个都好。这取决于你的情况。关于每个对象,您想了解什么?

正如 Patrick Roberts 在下面的评论中指出的那样,Fido.constructor 将是从 GreatDane 继承的实际构造函数。你可以修改它,所以如果你改变了构造函数,你的比较就会 return false.