js继承的实现

1.原型原型链

function Parent() {
  this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
  console.log('Hello');
};

function Child() {
  this.name = 'Child';
}
Child.prototype = new Parent();

var child = new Child();
child.sayHello(); // Hello

      1.1重点时子集的原型 强行被赋值 父级构造函数生成的实力

2. 构造函数继承

      

function Parent() {
  this.name = '张三';
}
function Child(name) {
  Parent.call(this)
}
var child = new Child('Child');
console.log(child.name);

    构造函数继承只能继承构造函数中的属性

3.组合继承

     

function Parent(name) {
  this.name = name;
}
Parent.prototype.sayHello = function() {
  console.log('Hello');
};

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

var child = new Child('Child');

4. 原型式继承

        

// 原型继承
inHeritObject(o) {
    // 创建一个过渡对象
    function F() {}
    // 将父类对象的给过渡对象的原型对象上
    F.prototype = o;
    // 返回新的实例化对象
    return new F();
}

o是个对像,他的构造函数中的属性和原型原型连上的都被继承

5.class继承 extends 实现继承需要在自己构造函数中使用super给父级构造函数属性赋值

6.寄生式继承(原型式继承和工厂模式)

     

function objectCopy(obj) {
  function Fun() { };
  Fun.prototype = obj;
  return new Fun();
}
 
function createAnother(obj) {
  let clone = objectCopy(obj);
  clone.showName = function () {
    console.log('my name is:', this.name);
  };
  return clone;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值