在 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
注意:以上几种方式都有各自的优缺点,需要根据具体需求选择合适的方式。