您的位置:首页 > 其它

详解原型链,面向对象(下)

2017-12-14 10:39 120 查看
接上文:

1.类的声明

function Animal (){
this.name="name";
}
es6:
class Animal2{
constructor(){
this.name="name";
}
}


2.生成实例 new Animal(),new Animal2,如果new的时候没有参数,也可以不加括号
3.继承的实现
>call方法(通过构造函数实现继承)



缺点:无法继承来自Parent1的原型上的东西,只能部分继承

>原型链继承



缺点:
改变了s1的属性同时也会影响到s2,因为原型链中的原型对象是公用的
注:实际上new出来的新类.name是不存在的,通过查找新类.__proto__.name才会有,所以是在原型链上查找出来的
>组合方式(企业通用方法)



缺点:new 2次,构造函数被执行了2次
第一次:s3的new时候 Child3的构造函数被执行了一次
第二次:Child3的原型new Parent3的时候
注:其实s3和s4分别有两套name和play,一份是call出来的,使用时直接s3.name,可以得出,一份是原型链上的s3.__proto__.name可以得出,该方法只是在call的基础上把parent的原型链继承给了Child3而已
>优化



缺点:constroctor指向父类
>优化
测试过程中也可以

function Parent4 () {
this.name = 'parent4';
this.play = [1, 2, 3];
}
function Child4 () {
Parent4.call(this);
this.type = 'child4';
}
Child4.prototype = Parent4.prototype;
Child4.prototype.constructor=Child4;
var s5 = new Child4();
var s6 = new Child4();
console.log(s5, s6);

console.log(s5 instanceof Child4, s5 instanceof Parent4);
console.log(s5.constructor);


将constructor设置回来即可,但是父类和子类的
constructor都变成子类了

>终极优化



var o=Object.create(parent)是把参数parent当做原型对象传给o的,所以o并不具备parent的属性,但是o的__proto__具有,因为o.__proto__===parent

总结:原型链继承由于new的时候是把原型对象上的属性复制给新对象,于是新对象相当于有两个相同属性,如果新对象为o,那么他既有o.name,又有o.__proto__.name,修改两个的时 候互不影响,但是会影响原型链就是原型对象的.prototype,继而影响所有new出来的新对象

如有错误,请多指正
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: