JavaScript中的原型与原型链
原创什么是原型
在JavaScript中,每个对象都有一个特殊的隐藏属性[[Prototype]](可通过__proto__访问),它要么是另一个对象,要么是null。这个对象就称为该对象的"原型"。
当我们需要读取一个对象的属性时,如果对象本身没有这个属性,JavaScript会自动从它的原型中寻找该属性,这就是所谓的"原型继承"。
const animal = { eats: true};const rabbit = { jumps: true};rabbit.__proto__ = animal; // 设置rabbit的原型为animalconsole.log(rabbit.eats); // true (从原型获取)console.log(rabbit.jumps); // true (来自自身)函数的prototype属性
每个函数都有一个prototype属性(箭头函数除外),这个属性指向一个对象,当这个函数作为构造函数使用时,这个对象会成为新创建对象的原型。
function Animal(name) { this.name = name;}Animal.prototype.eats = true; // 添加到原型const rabbit = new Animal('Rabbit');console.log(rabbit.eats); // true (来自原型)console.log(rabbit.name); // "Rabbit" (来自构造函数)原型链
JavaScript中对象的原型可能也有自己的原型,这样就形成了一条原型链。当访问一个属性时,JavaScript会沿着这条链向上查找,直到找到该属性或到达原型链的末端(null)。
const animal = { eats: true, walk() { console.log('Animal walks'); }};const rabbit = { jumps: true, __proto__: animal};const longEarRabbit = { earLength: 10, __proto__: rabbit};longEarRabbit.walk(); // Animal walks (从原型链继承)console.log(longEarRabbit.jumps); // true (从rabbit继承)原型相关方法
Object.create(proto) - 创建一个新对象,使用现有对象作为新对象的原型const animal = { eats: true};const rabbit = Object.create(animal);console.log(rabbit.eats); // trueObject.getPrototypeOf(obj) - 返回指定对象的原型const animal = {};const rabbit = Object.create(animal);console.log(Object.getPrototypeOf(rabbit) === animal); // trueObject.setPrototypeOf(obj, prototype) - 设置一个指定对象的原型const animal = { eats: true };const rabbit = { jumps: true };Object.setPrototypeOf(rabbit, animal);console.log(rabbit.eats); // true原型在实际开发中的应用
原型继承是JavaScript实现对象间共享属性和方法的主要方式。理解原型可以帮助我们:
实现高效的对象继承理解内置对象的属性和方法来源创建自定义类和方法// 自定义数组方法示例Array.prototype.last = function() { return this[this.length - 1];};const arr = [1, 2, 3];console.log(arr.last()); // 3需要注意的是,修改内置对象的原型(如Array、Object等)通常被认为是不好的实践,因为这可能导致与其他代码的冲突。
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权本站发表,未经许可,不得转载。
开发学习网


