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 原型鏈進行對象間的繼承和共享方法的實現。