JS原型链

  原型链

  1. 每一个实例都有自己的原型,可以__proto__访问
  2. 构造函数,通过new创建实例
  3. 构造函数通过prototype指向原型对象
  4. 原型对象通过constructor指向构造函数
  5. 如下图所示:
  6. 访问对象中的属性,如果不存在,那么会在原型中查找,如果还没有,继续在原型中查找

    继承

1 构造函数

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

  

2 原型链

child.prototype = new Parent()
缺点:当存在引用类型的时候,一个实例数据的改变,另一个也会改变,例如 P1.friend = ['Jany', 'LiMINg'],当P1增加一个朋友,另外的实例也会增加。

3 组合继承

把公共数据放在Parent中,这样的话就不会公用一个引用类型

1 function Parent(name) {
2     this.name = [‘Jang’,‘Dany’]
3 }
4 function Child(age) {
5     Parent.call(this);
6     this.age = age
7 }
8 child.prototype = new Parent()

 

4 优化组合继承

function Parent(name) {
    this.name = [‘Jang’,‘Dany’]
}
function Child(age) {
    Parent.call(this);
    this.age = age
}
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child

  

判断原型和实例的关系

1. instance instanceof object,只要是原型链中的都可以
2. object.prototyoe.isprototypeoof(instance)
3. object.prototype.tostring.call(instance)

  

posted @ 2018-08-08 12:56  dfgfgf  阅读(318)  评论(0)    收藏  举报