当前位置: 首页 > news >正文

JavaScript 原型(Prototype)详解

在 JavaScript 中,prototype(原型) 是实现继承的核心机制,它是每个 JavaScript 对象都拥有的内置属性,用于共享属性和方法。

核心概念

1. 原型是什么?

  • 每个 JavaScript 函数都有一个特殊的 prototype 属性(函数也是对象)
  • 这个 prototype 属性是一个对象,称为"原型对象"
  • 当使用 new 关键字创建实例时,实例会继承其构造函数的原型对象

2. 原型链如何工作?

function Person(name) {this.name = name;
}// 向原型添加方法
Person.prototype.greet = function() {return `Hello, I'm ${this.name}`;
};const alice = new Person("Alice");// 当访问 alice.greet() 时:
// 1. 先检查 alice 对象自身是否有 greet 方法 → 没有
// 2. 然后检查 alice.__proto__ (指向 Person.prototype) → 找到并执行
console.log(alice.greet()); // "Hello, I'm Alice"

3. 原型链可视化

alice 实例│├── 自身属性: name = "Alice"│└── __proto__ 指向 → Person.prototype│├── greet() 方法│└── __proto__ 指向 → Object.prototype│├── toString() 方法├── hasOwnProperty() 方法│└── __proto__ 指向 → null

关键属性和方法

1. prototype 属性

  • 存在于构造函数上
  • 用于定义将被所有实例继承的属性和方法
function Car(model) {this.model = model;
}// 向 Car 的原型添加方法
Car.prototype.drive = function() {return `${this.model} is driving`;
};

2. _ _ proto _ _ 属性(已弃用但广泛支持)

  • 存在于对象实例上
  • 指向创建该对象的构造函数的 prototype
  • 现代代码应使用 Object.getPrototypeOf()
const myCar = new Car("Tesla");
console.log(myCar.__proto__ === Car.prototype); // true
console.log(Object.getPrototypeOf(myCar) === Car.prototype); // true (推荐)

3. constructor 属性

  • 存在于原型对象上
  • 指回构造函数本身
console.log(Car.prototype.constructor === Car); // true
console.log(myCar.constructor === Car); // true (通过原型链访问)

原型继承实践

1. 基本继承实现

// 父类
function Animal(name) {this.name = name;
}Animal.prototype.eat = function() {return `${this.name} is eating`;
};// 子类
function Dog(name, breed) {Animal.call(this, name); // 调用父类构造函数this.breed = breed;
}// 设置原型链继承
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // 修复构造函数指向// 添加子类特有方法
Dog.prototype.bark = function() {return `${this.name} barks loudly!`;
};// 使用
const myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.eat()); // "Buddy is eating" (继承自 Animal)
console.log(myDog.bark()); // "Buddy barks loudly!" (自有方法)

2. ES6 类语法(基于原型的语法糖)

class Animal {constructor(name) {this.name = name;}eat() {return `${this.name} is eating`;}
}class Dog extends Animal {constructor(name, breed) {super(name); // 调用父类构造函数this.breed = breed;}bark() {return `${this.name} barks loudly!`;}
}const myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.eat()); // 继承方法
console.log(myDog.bark()); // 自有方法

原型相关的重要方法

1. Object.create()

创建一个新对象,使用现有对象作为新对象的原型

const animalPrototype = {eat() {return `${this.name} is eating`;}
};const rabbit = Object.create(animalPrototype);
rabbit.name = "Bunny";
console.log(rabbit.eat()); // "Bunny is eating"

2. Object.getPrototypeOf()

获取对象的原型

console.log(Object.getPrototypeOf(rabbit) === animalPrototype); // true

3. Object.setPrototypeOf()

设置对象的原型(不推荐在性能敏感代码中使用)

const bird = { name: "Tweety" };
Object.setPrototypeOf(bird, animalPrototype);
console.log(bird.eat()); // "Tweety is eating"

4. instanceof 操作符

检查对象是否在原型链中包含指定构造函数的原型

console.log(myDog instanceof Dog); // true
console.log(myDog instanceof Animal); // true
console.log(myDog instanceof Object); // true

原型的重要性

  1. 共享方法:所有实例共享原型上的方法,节省内存
  2. 动态更新:修改原型会影响所有已存在的实例
  3. 实现继承:JavaScript 中继承的核心机制
  4. 多态支持:通过原型链实现方法覆盖
// 动态更新示例
Animal.prototype.sleep = function() {return `${this.name} is sleeping`;
};console.log(myDog.sleep()); // "Buddy is sleeping" (即使实例已创建)

理解 JavaScript 的原型机制是掌握这门语言面向对象编程的关键。虽然 ES6 类语法提供了更直观的接口,但其底层实现仍然基于原型继承。

相关文章:

  • C#调用C++ 结构体方法
  • mapbox高阶,使用mbview发布mbtiles数据为矢量切片服务,并加载
  • 第五节 类型系统进阶-类型守卫(Type Guard)的实现方式
  • ubuntu22.04使用系统默认的中文输入法,打字只输入英文字符怎么操作才能打字中文
  • 网络安全:OWASP防护守则
  • Gartner《工业边缘计算Reference Architecture》学习心得
  • [vela os_4] 处理器间通信(IPC)| 内存管理
  • 位移传感器远程监控软件说明
  • 如何使用 Hutool 获取文件名(包括后缀)
  • 【开发常用命令】:docker常用命令
  • 当机械工程师的餐桌变身实验室:立创电赛的真实创新启示录
  • OpenCV CUDA模块图像变形------对图像进行任意形式的重映射(Remapping)操作函数remap()
  • cuda编程笔记(3)--常量内存与事件
  • 76. 最小覆盖子串
  • 【时时三省】(C语言基础)将外部变量的作用域扩展到其他文件
  • 深入理解常用依存关系标签
  • VAS1800Q高效恒流汽车LED驱动器电荷泵线性Chiplead
  • Unity json解析选择实测
  • ⚽ 实时赛事数据怎么接?WebSocket vs REST 接口详解!
  • 《TCP/IP协议卷1》第11章 UDP:用户数据报协议
  • 定制研发服务/泰州网站排名seo
  • 青海 住房和建设厅网站/seo网站外链平台
  • 做百度竞价用什么网站/企业网站推广公司
  • 有做外国人的零售网站吗/网站统计分析工具
  • 佛山营销网站建设服务/竞价网络推广外包
  • 网站底部特效/百度小说风云榜2022