您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

JavaScript 中的 instanceof 运算符

时间:12-14来源:作者:点击数:
城东书院 www.cdsy.xyz

instanceof 运算符 测试给定对象是否是给定 JavaScript 类 。

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

const obj = new Rectangle(3, 5);
obj.height; // 3
obj.width; // 5

// The `instanceof` keyword is how you test whether an object was created
// from a certain class.
obj instanceof Rectangle; // true
({}) instanceof Rectangle; // false

从技术上讲, instanceof 运算符检查 原型链 以查看原型链中的任何构造函数是否等于给定类。 这意味着如果您使用 继承 ,则子类的实例也是基类的实例。

class BaseClass {}
class SubClass extends BaseClass {}

const obj = new SubClass();

obj instanceof SubClass; // true
obj instanceof BaseClass; // true

对象类

Object class 是所有 JavaScript 类的基类。

class MyClass {}

const obj = new MyClass();

obj instanceof Object; // true
({}) instanceof Object; // true
null instanceof Object; // false

您可能很想使用 v instanceof Object 检查是否 v 是一个对象。 这适用于大多数情况,但 在某些情况下对象不是 instanceof Object( 2ality 商业网/2012/08/instanceof-object.html)。

// `Object.prototype` is not technically `instanceof Object` because
// prototype chains must end somewhere
typeof Object.prototype; // 'object'
Object.prototype instanceof Object; // false

// Setting a function's prototype to `Object.create(null)` means
// `Object` won't be in the object's prototype chain.
function MyClass() {}
MyClass.prototype = Object.create(null);

typeof new MyClass(); // 'object'
(new MyClass()) instanceof Object; // false

错误案例

这 instanceof 如果右侧不是函数,则运算符会引发错误。

class MyClass {}

function MyOtherClass() {}

const obj = {};

obj instanceof MyClass; // false
obj instanceof MyOtherClass; // false

// Throws "TypeError: Right-hand side of 'instanceof' is not callable"
obj instanceof { answer: 42 };
城东书院 www.cdsy.xyz
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐