您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在 ECMAScript (ES) 中,继承可以通过多种方式实现。以下是几种常见的方法:
这是最基本的继承方式,通过将子类的原型设置为父类的一个实例来实现继承。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello from ' + this.name);
};
function Child() {
this.name = 'Child';
}
Child.prototype = new Parent(); // 将 Child 的原型设置为 Parent 的一个实例
const child = new Child();
child.sayHello(); // 输出: Hello from Child
通过在子类构造函数中调用父类构造函数来实现继承。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello from ' + this.name);
};
function Child(name) {
Parent.call(this, name); // 调用父类构造函数
}
const child = new Child('Child');
console.log(child.name); // 输出: Child
child.sayHello(); // 报错: child.sayHello is not a function
结合原型链继承和构造函数继承的优点,既继承了父类的实例属性,又继承了父类的原型方法。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello from ' + this.name);
};
function Child(name) {
Parent.call(this, name); // 调用父类构造函数,继承实例属性
}
Child.prototype = new Parent(); // 将 Child 的原型设置为 Parent 的一个实例,继承原型方法
Child.prototype.constructor = Child; // 修复构造函数指向
const child = new Child('Child');
child.sayHello(); // 输出: Hello from Child
通过创建一个新对象,并将这个对象的原型设置为另一个对象来实现继承。
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
const parent = {
name: 'Parent',
sayHello: function() {
console.log('Hello from ' + this.name);
}
};
const child = object(parent);
child.name = 'Child';
child.sayHello(); // 输出: Hello from Child
在原型式继承的基础上,增强对象。
function createObj(o) {
const clone = object(o);
clone.sayHello = function() {
console.log('Hello from ' + this.name);
};
return clone;
}
const parent = {
name: 'Parent'
};
const child = createObj(parent);
child.name = 'Child';
child.sayHello(); // 输出: Hello from Child
这是最常用的继承方式,通过原型链继承原型方法,通过构造函数继承实例属性。
function inheritPrototype(subType, superType) {
const prototype = Object.create(superType.prototype); // 创建对象,其原型为 superType 的原型
prototype.constructor = subType; // 增强对象,弥补因重写原型而失去的默认的 constructor 属性
subType.prototype = prototype; // 指定对象,将子类原型指向这个对象
}
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello from ' + this.name);
};
function Child(name) {
Parent.call(this, name); // 调用父类构造函数,继承实例属性
}
inheritPrototype(Child, Parent);
const child = new Child('Child');
child.sayHello(); // 输出: Hello from Child
这些方法各有优缺点,选择哪种方法取决于具体的需求和场景。寄生组合式继承是目前最推荐的方式,因为它结合了原型链继承和构造函数继承的优点,避免了它们的缺点。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。