JavaScript 原型链是一种实现对象间继承的机制。要更便捷地使用原型链,可以遵循以下几点:
class Parent { constructor() { this.parentProperty = 'parent'; } parentMethod() { console.log('This is a method in the parent class.'); } } class Child extends Parent { constructor() { super(); this.childProperty = 'child'; } childMethod() { console.log('This is a method in the child class.'); } }
Object.create()
:Object.create()
方法允许你基于现有对象创建一个新对象,同时设置新对象的原型。这使得继承更加简单。例如:const parent = { parentProperty: 'parent', parentMethod() { console.log('This is a method in the parent object.'); }, }; const child = Object.create(parent); child.childProperty = 'child'; child.childMethod = function () { console.log('This is a method in the child object.'); };
function Parent() {} Parent.prototype.sharedMethod = function () { console.log('This is a shared method.'); }; Parent.prototype.sharedProperty = 'shared'; function Child() {} Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; Child.prototype.childMethod = function () { console.log('This is a method in the child class.'); };
extends
关键字:在子类中使用 extends
关键字继承父类,可以简化代码并提高可读性。例如:class Child extends Parent { constructor() { super(); this.childProperty = 'child'; } childMethod() { console.log('This is a method in the child class.'); } }
遵循这些建议,可以让你更便捷地使用 JavaScript 原型链进行对象间的继承和共享方法的实现。