🍓JavaScript 对象原型链继承的弊端 🍓

🍂确定实例与原型的关系
console.log(A ininstanceof B)
//A是B的实例? console.log(A.prototype.isPrototypeOf(B))//A是B的实例 🍂在通过原型链实现继承时,给原型添加新方法的动作务必放在替换原型之后,即
function Animal(){} function Dog(){} Dog.prototype = new Animal(); Dog.prototype.fn1 = function(){//这一步务必放在替换对象之后,否则会被覆盖掉 console.log('fn1); } 🍂在通过原型链实现继承后,创建原型方法时不能使用对象字面量的方式 ... Dog.prototype = new Animal(); Dog.prototype = {//错误!这样做相当于重写整个Dog.prototype fn1: function(){...}, fn2: function()(...) } //以下才是正确姿势 Dog.prototype.fn1 = function(){...}; Dog.prototype.fn2 = function(){...}; 🍂通过原型链实现继承,当父类原型中存在引用类型值(如数组,json等)时,对子类实例的修改会影响到父类原型的值~
let Person = function(){}; Person.prototype.arr = [
'orange','apple','banana']; let Person2 = function(){}; Person2.prototype = new Person();//Person2 继承 Person let person2 = new Person2(); console.log(person2.arr);//['orange','apple','banana'] person2.arr.push('strawberry'); let person22 = new Person2(); console.log(person22.arr);//['orange','apple','banana','strawberry'] console.log(person2.arr);//['orange','apple','banana','strawberry'] let person = new Person(); console.log(,person.arr);//['orange','apple','banana','strawberry'] //改变子类的引用类型值arr的值,使超类的arr也受到了影响 //创建对象有很多方法,但大多都各有弊端(详见《高程》)。不过有了ES6的class之后,我就抛弃其他方法啦~强烈推荐使用class

 其实都是书上的内容,你问我为啥要自己再写一遍?加深印象呗~

posted @ 2018-11-09 13:09  LLLLily  阅读(358)  评论(0编辑  收藏  举报