在 JavaScript 中,有幾種方法可以實現繼承:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {}
Child.prototype = new Parent();
const child = new Child();
console.log(child.name); // 輸出 'Parent'
child.sayHello(); // 輸出 'Hello'
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
const child = new Child();
console.log(child.name); // 輸出 'Parent'
child.sayHello(); // 報錯:child.sayHello is not a function
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.name); // 輸出 'Parent'
child.sayHello(); // 輸出 'Hello'
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.name); // 輸出 'Parent'
child.sayHello(); // 輸出 'Hello'
這些都是常見的實現繼承的方法,每種方法都有自己的優(yōu)缺點,可以根據具體情況選擇合適的方法。