原生js写继承

js中实现继承的方法:

假设现在存在一个构造函数想继承另一个构造函数。

function Friend(){
  this.friend="xiaohua";
}
function Person(name,age){
    this.name=name;
    this.age=age;
    this.sayName=function(){
      console.log("hello,my name is " +this.name+" nice to meet you")
    };
}

1、仅通过构造函数

在构造函数内部通过改变要继承的构造函数的this指向;

function Person(name,age){
    Friend.apply(this,arguments);//添加了这一行
    this.name=name;
    this.age=age;
    this.sayName=function(){
      console.log("hello,my name is " +this.name+" nice to meet you.my friend is "+this.friend)
    };//在这里就可使用this访问friend了
}

2、原型链方式实现继承

删除构造函数中调用Friend构造函数的表达式;改变Person构造函数的原型对象

Person.prototype=new Friend();
person.prototype.constructor=Person;

3、直接继承prototype

直接继承Friend的prototype,不经过构造函数,删除Friend构造函数中的表达式。

Friend.prototype.friend="xiaohua";
liming.prototype=Friend.prototype;
liming.prototype.constructor=Person;

缺点:两个构造函数共享同一个原型对象,只要对其中的一个prototype进行改变。两个构造函数的饿实例都会受到影响。

4、创建一个新的空对象作为传递的媒介

这里创建一个函数extend:

function extend(child,parent){
  var F=function(){};
  F.prototype=parent.prototype;
  child.prototype=new F();
  child.prototype.constructor=child;
}

感觉没什么缺点。比寄生组合式继承多了一层查找的层次。

5、拷贝继承(要继承的属性必须全部在要继承的函数的原型对象中才行)

将Friend()原型对象的所有属性复制一份到Person的原型对象中。这里创建另一个函数extend2

function extend2(child,parent){
  var p=parent.prototype,c=child.prototype;
  for(var key in p){
    c[key]=p[key];
  }
}

缺点:不能实时更新对Friend的继承关系;

6、寄生组合式继承

创建一个函数:object.create()创建一个对超类的原型对象的浅复制。

function inheritFri(child,parent){
  var prototype=object.create(parent.prototype);
  prototype.constructor=child;
  child.prototype=prototype;
}

详细请见:阮一峰大大:http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance.html

 JavaScript 的继承与多态:https://juejin.im/post/5912753ba22b9d005817524e

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值