JavaScript中如何判断对象属于某个类?方法分享!

22 min read

在 JavaScript 中没有类的概念,但是可以使用构造函数来模拟类的概念。判断一个对象是否属于某个构造函数可以通过以下方法:

  1. 使用 instanceof 运算符:
function Person(name) {
  this.name = name;
}

var person = new Person("John");

console.log(person instanceof Person); // true
  1. 使用 constructor 属性:
function Person(name) {
  this.name = name;
}

var person = new Person("John");

console.log(person.constructor === Person); // true
  1. 使用 Object.prototype.toString 方法:
function Person(name) {
  this.name = name;
}

var person = new Person("John");

console.log(Object.prototype.toString.call(person) === "[object Person]"); // true

其中第三种方法需要在构造函数中给出 toString 方法的实现,如下所示:

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

Person.prototype.toString = function() {
  return "[object Person]";
};

var person = new Person("John");

console.log(Object.prototype.toString.call(person) === "[object Person]"); // true