在 ES5 中,可以通過以下方式實現繼承:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
function Child() {
this.age = 18;
}
Child.prototype = new Parent();
var child = new Child();
child.sayHello(); // 輸出: Hello, Parent
call
或 apply
方法將父類的屬性和方法綁定到子類實例上。示例代碼如下:function Parent() {
this.name = 'Parent';
}
function Child() {
Parent.call(this);
this.age = 18;
}
var child = new Child();
console.log(child.name); // 輸出: Parent
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
function Child() {
Parent.call(this);
this.age = 18;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child();
child.sayHello(); // 輸出: Hello, Parent
Object.create
方法創建一個新對象,并將父類實例對象作為新對象的原型。示例代碼如下:function createObject(proto) {
function F() {}
F.prototype = proto;
return new F();
}
var parent = {
name: 'Parent',
sayHello: function() {
console.log('Hello, ' + this.name);
}
};
var child = createObject(parent);
child.sayHello(); // 輸出: Hello, Parent
function createChild(parent) {
var child = Object.create(parent);
child.age = 18;
return child;
}
var parent = {
name: 'Parent',
sayHello: function() {
console.log('Hello, ' + this.name);
}
};
var child = createChild(parent);
child.sayHello(); // 輸出: Hello, Parent
注意:以上幾種方式都有各自的優缺點,需要根據具體需求選擇合適的方式。