3

JavaScript instanceof 运算符

 1 year ago
source link: https://www.myfreax.com/javascript-instanceof/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
JavaScript instanceof 运算符

JavaScript instanceof 运算符

在本教程中,您将学习如何使用 JavaScript instanceof 运算符来确定构造函数的原型是否在对象的原型链。

JavaScript instanceof 操作符介绍

如果构造函数的原型 (constructor.prototype) 出现在对象的原型链中,则 instanceof 运算符返回 true。

下面显示 instanceof 运算符的语法:

object instanceof contructor

在这个语法中:

  • object 是要测试的对象。
  • constructor 是一个用来测试的函数。

JavaScript instanceof 运算符示例

以下示例定义 Person 类型并使用 instanceof 运算符检查对象是否是 Person 类型的实例:

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

let p1 = new Person('John');

console.log(p1 instanceof Person); // true

怎么运行的。

首先,使用构造函数模式定义一个类型 Person

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

其次,创建 Person 类型对象 p1:

let p1 = new Person('John Doe');

第三,检查 p1 是否是 Person 类型的实例:

console.log(p1 instanceof Person); // true

它返回 true,因为 Person.prototype 出现在 p1 对象的原型链。 p1 的原型链是 p1、Person.prototype 和 Object.prototype 之间的链接:

JavaScript-instanceof.svg

以下也返回 true,因为 Object.prototype 出现在 p1 对象的原型链:

console.log(p1 instanceof Object); // true

ES6 类和 instanceof 运算符

以下示例定义 Person 类并使用 instanceof 运算符检查对象是否是 Person 类的实例

class Person {
  constructor(name) {
    this.name = name;
  }
}

let p1 = new Person('John');

console.log(p1 instanceof Person); // true

怎么运行的。

首先,定义 Person 类:

class Person {
  constructor(name) {
    this.name = name;
  }
}

其次,创建 Person 类的实例:

let p1 = new Person('John');

第三,检查p1是否是 Person 类的实例:

console.log(p1 instanceof Person); // true

instanceof 运算符和继承

以下示例定义Employee 类并继承 Person 类:

class Person {
  constructor(name) {
    this.name = name;
  }
}

class Employee extends Person {
  constructor(name, title) {
    super(name);
    this.title = title;
  }
}

let e1 = new Employee();

console.log(e1 instanceof Employee); // true
console.log(e1 instanceof Person); // true
console.log(e1 instanceof Object); // true

由于 e1Employee 类的一个实例,它也是类 PersonObject 类的一个实例。

Symbol.hasInstance

在 ES6 ,instanceof 运算符使用 Symbol.hasInstance 函数来检查关系。 Symbol.hasInstance() 接受一个对象参数,如果对象作为该类实例时返回 true。 例如:

class Person {
  constructor(name) {
    this.name = name;
  }
}

let p1 = new Person('John');

console.log(Person[Symbol.hasInstance](p1)); // true

由于 Symbol.hasInstance 是在 Function 原型定义的,因此默认情况下它在所有函数和类可用。

您可以将子类的 Symbol.hasInstance 重新定义为静态方法。例如:

class Person {
  constructor(name) {
    this.name = name;
  }
}

class Android extends Person {
  static [Symbol.hasInstance]() {
    return false;
  }
}

let a1 = new Android('Sonny');

console.log(a1 instanceof Android); // false
console.log(a1 instanceof Person); // false
  • 使用 instanceof 运算符检查 constructor.protoype 是否在对象的原型链。

微信公众号

支付宝打赏

myfreax 淘宝打赏

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK