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 继承 Parent

let 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 种方式。每种方式都有其特点和应用场景,可以根据具体需求选择合适的方式来实现继承。

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值