检查实例是否以不同的方式声明的对象



我正在阅读有关如何在JavaScript中声明对象的阅读。

有对象字面的方式和基于函数的方式。在以下代码中,我使用基于函数的对象创建一个名为Person1的对象,而Person2则创建一个对象。

我然后尝试检查他们的实例。对于person2,我得到了" true",但是对于person1,我得到了" typeError:'instance of'的右侧不可呼应"

var Person1 = {
  name: "John"
}
function Person2() {
  this.name = "Jane";
}
var bob = Person1;
var bobby = new Person2();
console.log(bob instanceof Person1);
console.log(bobby instanceof Person2);

如何使用对象文字创建对象,并且仍然获得正确的实例?

you can 做到这一点,但是您确实不应该Symbol.hasInstance允许您超载instanceof的行为:

var Person1 = {
  name: "John",
  [Symbol.hasInstance](instance) {
    return instance === this;
  }
}
function Person2() {
  this.name = "Jane";
}
var bob = Person1;
var bobby = new Person2();
console.log(bob instanceof Person1);
console.log(bobby instanceof Person2);

但是,您应该做的是:

function Person(name) {
  this.name = name;
}
// confusing variable names if you ask me
var bob = new Person('John');
var bobby = new Person('Jane');
console.log(bob instanceof Person);
console.log(bobby instanceof Person);

Person1是指{name: "John"} object不是constructor,因此您不能在Person1上执行instanceof

Person2constructor,因此您可以在Person2上进行instanceof

var Person1 = {
	name: "John"
}
function Person2() {
	this.name = "Jane";
}
var bob = Person1;
var bobby = new Person2("john");
    
console.log(bob === Person1) //true
console.log(bob instanceof Object) //true
console.log(bobby instanceof Person2) //true
console.log(bobby instanceof Object) //true
console.log(bobby === Person2) //false

最新更新