检查instanceof以声明不同的对象

时间:2018-02-22 18:16:46

标签: javascript

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

有对象文字方式和基于功能的方式。在下面的代码中,我使用object literal创建一个名为Person1的对象,使用基于函数的Person2创建一个对象。

然后我尝试检查他们的实例。对于Person2,我得到了#34; true"但对于Person1,我得到了#34; TypeError:' instanceof'的右侧是不可调用的"

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);

如何使用object literal创建对象并仍然获得正确的instanceof?

2 个答案:

答案 0 :(得分:1)

更正,你可以这样做,但你真的不应该。使用Symbol.hasInstance可以重载instanceof的行为:

var Person1 = {
  name: "John",
  [Symbol.hasInstance] (obj) {
    return obj == 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 = "Jane";
}

// 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);

答案 1 :(得分:0)

Person1引用{name: "John"} object而不是constructor,因此您无法instanceof {/ 1} Person1 >

Person2constructor,因此您可以在instanceofPerson2



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