zoukankan      html  css  js  c++  java
  • 原型链

    通过将一个构造函数的原型对象指向父类的实例,就可以调用父类中的实例属性及父类的原型对象属性,实现继承。

    function animals(){
        this.type = "animals";
        this.emotion = ["喜","怒","哀","乐"];
    }
    animals.prototype.eat = function(){
        console.log("吃吃吃");
    }
    animals.prototype.drink = function(){
        console.log("喝喝喝");
    }
    function dog(){
        this.type = "dog";
        // animals.call(this);
    }
    dog.prototype = new animals();
    // console.log(dog.prototype.constructor);
    // dog.prototype.constructor = dog;
    // console.log(dog.prototype.constructor);
    
    var d = new dog();
    console.log(d.emotion);
    d.emotion.push("愁");
    console.log(d.emotion);
    console.log(d);
    d.eat();
    
    var d2 = new dog();
    console.log(d2.emotion);
    console.log(d2);

    dog.prototype = new animals();可以调用animals中的实例属性及animals中的原型对象属性,

    var d = new dog();创建了dog的一个实例,可以调用dog中的实例属性,然后调用dog的原型对象属性,因为他的原型对象指向animals的一个实例,此时会调用animals中的实例属性,最后调用animals中的原型对象属性。

    结果如上,d,d2实例中的内容均为构造函数dog中的属性内容,当在一个实例中改变emotion的内容时,父类中的emotion也会改变,下一个实例调用时,内容为改变之后的。

    在实例中改变父类中属性内容时,父类中的属性不会被改变;除非改变的是引用类型的内容。

    若是在构造函数dog中加上animals.call(this);,即借用构造函数调用,

    结果如上,d,d2中的内容均为animals构造函数中的属性内容,因为在dog构造函数中调用了animals构造函数,会拷贝animals函数中的属性内容,但animals原型对象中的属性不会读写拷贝,若是没有dog.prototype = new animals();这一句,当d.eat();执行时将会报错,无法读取animals原型对象中的属性。

    当在实例中改变emotion值时,其他实例中该值未被改变,因为在各自的实例中都拷贝了一份animals构造函数中的属性。

    若是想要既实现在实例中改变值,但父类中值不改变,还能实现代码复用的简便性,可以将animals.call(this);与dog.prototype = new animals();结合起来使用。

    参考博客:https://www.cnblogs.com/sarahwang/p/9098044.html

  • 相关阅读:
    149. Max Points on a Line(js)
    148. Sort List(js)
    147. Insertion Sort List(js)
    146. LRU Cache(js)
    145. Binary Tree Postorder Traversal(js)
    144. Binary Tree Preorder Traversal(js)
    143. Reorder List(js)
    142. Linked List Cycle II(js)
    141. Linked List Cycle(js)
    140. Word Break II(js)
  • 原文地址:https://www.cnblogs.com/5201314m/p/10287950.html
Copyright © 2011-2022 走看看