原型链
- 每一个实例都有自己的原型,可以__proto__访问
- 构造函数,通过new创建实例
- 构造函数通过prototype指向原型对象
- 原型对象通过constructor指向构造函数
- 如下图所示:
- 访问对象中的属性,如果不存在,那么会在原型中查找,如果还没有,继续在原型中查找
-
继承
1 构造函数
1234567function
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 优化组合继承
123456789function
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
判断原型和实例的关系
1231. instance
instanceof
object,只要是原型链中的都可以
2. object.prototyoe.isprototypeoof(instance)
3. object.prototype.tostring.call(instance)
-