举例说明constructor和instanceof的区别是什么?

在 JavaScript 前端开发中,constructorinstanceof 常常一起讨论,但它们扮演着不同的角色,用于不同的目的。 让我们通过例子来区分它们:

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
posted @   王铁柱6  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示