欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > Js实现继承的6种方式

Js实现继承的6种方式

2024/10/25 12:20:54 来源:https://blog.csdn.net/yuzhochaojiwudib/article/details/142034279  浏览:    关键词:Js实现继承的6种方式

JavaScript 中实现继承的 6 种方式包括:

  1. 原型链继承
  2. 借用构造函数继承
  3. 组合继承(原型链 + 借用构造函数)
  4. 原型式继承
  5. 寄生式继承
  6. 寄生组合式继承

下面是每种方式的详细代码示例:

1. 原型链继承
javascriptfunction Parent() {
this.name = 'Parent';
this.play = [1, 2, 3];
}function Child() {
this.type = 'Child';
}Child.prototype = new Parent(); // Child 继承 Parentlet child1 = new Child();
let child2 = new Child();console.log(child1.name); // Parent
console.log(child1.play === child2.play); // true
2. 借用构造函数继承
javascriptfunction Parent() {
this.name = 'Parent';
this.play = [1, 2, 3];
}function Child() {
Parent.call(this); // 借用 Parent 构造函数
this.type = 'Child';
}let child1 = new Child();
let child2 = new Child();console.log(child1.name); // Parent
console.log(child1.play === child2.play); // false
3. 组合继承(原型链 + 借用构造函数)
javascriptfunction Parent() {
this.name = 'Parent';
this.play = [1, 2, 3];
}function Child() {
Parent.call(this); // 借用 Parent 构造函数
this.type = 'Child';
}Child.prototype = new Parent(); // Child 继承 Parent 的原型链
Child.prototype.constructor = Child; // 修复构造函数指向let child1 = new Child();
let child2 = new Child();console.log(child1.name); // Parent
console.log(child1.play === child2.play); // true
4. 原型式继承
javascriptfunction object(o) {
function F() {}
F.prototype = o;
return new F();
}let parent = {
name: 'Parent',
play: [1, 2, 3]
};let child = object(parent);
child.type = 'Child';console.log(child.name); // Parent
console.log(child.play === parent.play); // true
5. 寄生式继承
javascriptfunction createAnother(original) {
let clone = object(original); // 通过原型式继承创建对象
clone.sayHello = function() {
console.log('Hello from clone');
};
return clone;
}let parent = {
name: 'Parent',
play: [1, 2, 3]
};let child = createAnother(parent);
child.type = 'Child';console.log(child.name); // Parent
console.log(child.play === parent.play); // true
child.sayHello(); // Hello from clone
6. 寄生组合式继承
javascriptfunction inheritPrototype(child, parent) {
let F = function() {};
F.prototype = parent.prototype;
child.prototype = new F();
child.prototype.constructor = child;
}function Parent() {
this.name = 'Parent';
this.play = [1, 2, 3];
}function Child() {
Parent.call(this);
this.type = 'Child';
}inheritPrototype(Child, Parent);let child1 = new Child();
let child2 = new Child();console.log(child1.name); // Parent
console.log(child1.play === child2.play); // false

以上示例展示了 JavaScript 中实现继承的 6 种方式。每种方式都有其特点和应用场景,可以根据具体需求选择合适的方式来实现继承。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com