js之继承

1.原型链继承(Prototypal Inheritance)

原型链继承是完成继承最直接的方式。这会涉及到两个过程:创建新对象和重置构造器引用。首先,我们创建一个新构造函数,然后将它的prototype属性指向一个父类的实例。

function Parent() {
  this.name = 'parent';
}

function Child() {
  this.age = 27;
}

Child.prototype = new Parent();
var child = new Child();

console.log(child.name); // 输出: "parent"

2.构造函数继承(Constructor Inheritance)

这种方法共享了方法,在子构造函数中通过call或apply方法调用父构造函数。这样做可以使子构造函数具有父构造函数的所有属性,并且所有的属性方法都不会被共享。

function Parent() {
  this.names = ["John", "Stella"];
}

function Child() {
  Parent.call(this);
}

var child1 = new Child();
var p = new Parent();

child1.names.push("New name");

console.log(child1.names); // 输出: ["John", "Stella", "New name"]
console.log(p.names); // 输出: ['John', 'Stella']

3.组合继承(Combination Inheritance)

组合继承结合了原型链继承和构造函数继承的方式,通过在prototype上定义方法实现函数复用,又能保证每个实例有自己的属性。

function Parent(name) {
  this.names = ["John", "Stella"];
  this.name = name;
}

Parent.prototype.getName = function() {
  console.log(this.name);
}

function Child(name) {
  Parent.call(this, name);
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

var child1 = new Child("Tom");

console.log(child1.names); // 输出: ["John", "Stella"]
child1.getName(); // 输出: "Tom"

4.原型式继承(Prototypal Inheritance)

这是ES5引入的Object.create方法实现的原型式继承,我们选中一个对象作为创建新的对象的基础。

var parent = {
  names: ["John", "Stella"]
};

var child = Object.create(parent);
child.names.push("New name");

console.log(child.names); // 输出: ["John", "Stella", "New name"]

5.寄生式继承(Parasitic Inheritance)

寄生式继承的思路是创造一个用作继承的父对象的副本,并增强这个副本,然后返回这个副本。

function createAnother(original) {
  var clone = Object.create(original);
  clone.sayHi = function() {
    console.log("Hi!");
  };
  return clone;
}

var parent = {
  names: ["John", "Stella"]
};

var child = createAnother(parent);

child.sayHi(); // 输出: "Hi!"

6.寄生组合式继承(Parasitic Combination Inheritance)

寄生组合式继承(也被称为类式继承)是指通过借用构造函数来继承属性,通过原型链的形式来继承方法。本质上,该方法只调用了一次父类构造函数,并且避免在子类.prototype上创建不必要的、多余的属性。

function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

Parent.prototype.getName = function() {
  return this.name;
}

function Child(name, age) {
  Parent.call(this, name); // 通过借用构造函数来继承属性
  this.age = age;
}

Child.prototype = Object.create(Parent.prototype); // 通过原型链的形式来继承方法
Child.prototype.constructor = Child;

var child1 = new Child("Tom", 22);

console.log(child1.name); // 输出: "Tom"
child1.getName(); // 输出: "Tom"

7.ts里通过extends关键字实现继承

class DaChao extends Parent {}
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值