javascript中手动实现原型继承的核心是操作对象的[[prototype]]链,主要有两种方式:1. 使用object.create(),可直接创建以指定对象为原型的新对象,适合对象间直接继承;2. 通过构造函数结合prototype属性,将子类原型指向父类原型(child.prototype = object.create(parent.prototype)),并修正constructor指向,适用于模拟类式继承。理解手动继承有助于掌握js原型本质,避免this指向错误、constructor丢失、引用属性共享、for...in遍历原型属性及属性遮蔽等问题。

JavaScript中手动实现原型继承,核心就是通过操作对象的
[[Prototype]]
Object.create()
prototype

说白了,手动实现原型继承,无非就是两种常见思路:
Object.create()
这是我个人觉得最直接、最优雅的方式之一,尤其当你只想让一个对象继承另一个对象,而不需要通过构造函数来实例化时。它允许你创建一个新对象,并指定它的原型。

// 父对象(或者说,你想继承的那个原型对象)
const parent = {
value: 10,
getValue() {
return this.value;
}
};
// 子对象,以 parent 为原型创建
const child = Object.create(parent);
child.value = 20; // 覆盖父对象的 value
console.log(child.getValue()); // 输出 20
console.log(Object.getPrototypeOf(child) === parent); // true
// 内部的 [[Prototype]] 链接被正确设置了这里
child
getValue
parent
getValue
prototype
这是ES6
class
prototype

// 父类构造函数
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}.`);
};
// 子类构造函数
function Child(name, age) {
Parent.call(this, name); // 继承父类的属性
this.age = age;
}
// 核心:让 Child 的原型链指向 Parent 的原型对象
// 这样 Child 的实例就能访问 Parent.prototype 上的方法
Child.prototype = Object.create(Parent.prototype);
// 修正 constructor 指向,这步很重要,不然 constructor 会指向 Parent
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() {
console.log(`I am ${this.age} years old.`);
};
const childInstance = new Child('Alice', 5);
childInstance.sayHello(); // Hello, my name is Alice.
childInstance.sayAge(); // I am 5 years old.
console.log(childInstance instanceof Child); // true
console.log(childInstance instanceof Parent); // true这种方式稍微复杂一点,但它模拟了经典的类继承模式。
Object.create(Parent.prototype)
Parent.prototype
Child.prototype
child
parent
class
说实话,这个问题我被问过好几次,每次我的答案都差不多:理解手动原型继承,不仅仅是为了应对老旧代码,更重要的是为了真正理解JavaScript这门语言的“骨架”。ES6的
class
在我看来,理解这些底层机制,就像你学开车,不能只知道踩油门刹车,还得懂点发动机原理。当你遇到一些奇奇怪怪的bug,或者需要做一些性能优化时,对原型链的深刻理解能帮你快速定位问题。比如,你可能会发现某个方法调用不对劲,一查才发现原型链上挂错了东西,或者
this
Object.create()
prototype
这两种方式,虽然都能实现原型继承,但它们的侧重点和适用场景还是有挺大区别的。
Object.create()
new
Object.create()
Object.create()
而通过修改构造函数的
prototype
new
Parent.call(this, ...)
class
简单来说,
Object.create()
prototype
说实话,手动实现原型继承,确实有几个地方是新手容易踩坑的。
一个很经典的“坑”就是this
this
接着,就是constructor
Child.prototype = Object.create(Parent.prototype)
Child.prototype
constructor
parent
child
instanceof
instance.constructor
Child.prototype.constructor = Child;
再一个,是关于引用类型属性的共享问题。如果你的原型对象上有一个引用类型的属性(比如一个数组或对象),那么所有继承自这个原型的实例,都会共享这个引用。这意味着,如果你在一个实例上修改了这个引用类型的属性,所有其他实例上的这个属性也会跟着改变。这通常不是你想要的结果。解决办法通常是在构造函数内部创建实例独有的引用类型属性,而不是放在原型上。
还有一个小点,就是for...in
hasOwnProperty()
最后,就是属性的“遮蔽”(shadowing)。当一个实例拥有与原型链上同名的属性时,实例自身的属性会“遮蔽”原型上的属性。这意味着,当你访问这个属性时,会优先访问到实例自身的属性。这通常是预期的行为,但如果不理解,有时也会导致一些困惑。
以上就是js如何手动实现原型继承的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号