举例说明constructor和instanceof的区别是什么?
在 JavaScript 前端开发中,constructor
和 instanceof
常常一起讨论,但它们扮演着不同的角色,用于不同的目的。 让我们通过例子来区分它们:
1. constructor
属性:
constructor
属性指向创建对象的函数。 对于所有对象,constructor
属性都是可继承的。 这意味着如果一个对象没有显式定义 constructor
,它将继承其原型对象的 constructor
。
function Person(name) {
this.name = name;
}
const person1 = new Person("Alice");
console.log(person1.constructor === Person); // true,person1 由 Person 构造函数创建
console.log(person1 instanceof Person); // true,person1 是 Person 的实例
// 原型链继承
function Student(name, major) {
Person.call(this, name); // 调用父构造函数
this.major = major;
}
Student.prototype = Object.create(Person.prototype); // 原型继承
const student1 = new Student("Bob", "Computer Science");
console.log(student1.constructor === Person); // true,继承自 Person.prototype
console.log(student1.constructor === Student); // false
console.log(student1 instanceof Student); // true
console.log(student1 instanceof Person); // true
// 修复 constructor 指向
Student.prototype.constructor = Student; // 将 constructor 指回 Student
console.log(student1.constructor === Student); // true,constructor 现在指向 Student
console.log(student1.constructor === Person); // false
// 内置对象
const arr = [];
console.log(arr.constructor === Array); // true,数组由 Array 构造函数创建
2. instanceof
运算符:
instanceof
运算符用于检查一个对象是否是另一个构造函数的实例。它会沿着原型链向上查找,直到找到匹配的构造函数或到达原型链的顶端 (null)。
function Animal(name