JS實現繼承的3種方式

這是我參與8月更文挑戰的第5天,活動詳情查看:8月更文挑戰markdown

  • 一、 原型繼承方式app

    function Person(name,age){
        this.name = name;
        this.age = age;
    }
    
    Person.prototype.sayHello = function(){
        console.log("使用原型獲得名字:%s,年齡:%d",this.name,this.age);
    }
    
    function Student(){
    
    }
    Student.prototype = new Person("Jay",37);
    Student.prototype.grade=5;
    Student.prototype.tips=function(){
        console.log("我是從Student來的,年級是%d,繼承來的%s",this.grade,this.name);
    }
    
    var stu = new Student();
    stu.tips();
    複製代碼
    • 首先咱們建立一個方法做爲父類Person,再建立一個方法做爲子類Student,子類用原型去接收父類構造函數,這樣作一個指向關係從而達到子類繼承父類方法。子類也能夠添加本身的方法,這樣最後在實例化子類Student的時候,能夠從原型上拿到父類指向的函數。利用了原型鏈的特性每一級別的查找。

    二、 構造函數方式函數

    //父類函數
    function Parent(name){
        this.name = name;
        this.sayHello = function(){
            console.log("Parent Name : %s",this.name);
        }
    }
    
    //子類函數
    function Child(name,age){
        this.tempMethod = Parent;
        this.tempMethod(name);
        this.age = age;
        this.sayChild = function(){
            console.log("Child Name:%s,Age:%d",this.name,this.age);
        }
    }
    //測試繼承
    var p = new Parent("Kvkens");
    p.sayHello();
    
    var c = new Child("Kvkens",29);
    c.sayChild();
    複製代碼
    • 構造函數是用到了一箇中間函數做爲中間人,接收Parent函數,而且調用中間函數傳入相應構造參數,這裏可以直接調用Parent是由於固然環境是實例化,都是在new的時候發生的,並非靜態的函數。

    三、 call、apply 方式post

    function Animal(name,age,love){
        this.name = name;
        this.age = age;
        this.love = love;
        this.sayHi = function(){
            console.log("Animal name:%s,age:%d,love:%s",this.name,this.age,this.love);
        }
    }
    
    function Dog(name,age,love){
        Animal.call(this,name,age,true);
    }
    var dog = new Dog("xiaobai",5,true);
    dog.sayHi();
    複製代碼
    • 很是簡單的繼承實現,採用侵入式做用域劫持方式,我說的和別人解釋的不同,只是我本身的理解,如說的不對請指出,代碼會寫,有的時候卻不能說出爲何是這樣,都是本身的理解,見諒!
相關文章
相關標籤/搜索