js 實現繼承

來源:互聯網
上載者:User

標籤:繼承   cti   arguments   style   利用   type   部分   prot   on()   

我們現在要做的一件事情是像其他語言的物件導向一下實現繼承多態

具體要求如下:

一個 Father 建構函式,一個 Child 建構函式,其中改寫 Father中的部分參數, new Child() 表示出一個新的child

        var Father = function (name) {            this.name = name            this.say = function () {                console.log(‘i am ‘ + name)            }        }        var Child = function (name,age) {            this.age = age;            this.say = function () {                console.log("name:" + this.name + " and age:" + this.age);            }        }          Child.prototype = new Father()        var he = new Child(‘asd‘,12)
     console.log(he.firstName) // qiao
        console.log(he.name)          console.log(he.age)        he.say()    

 無法輸出 name 是因為不能穿參數

    var Father = function (name) {            this.name = name            this.firstName = ‘qiao‘            this.say = function () {                console.log(‘i am ‘ + name)            }        }        var Child = function (name,age) {            this.tempMethod = Father            this.tempMethod(name)            this.age = age;            this.say = function () {                console.log("name:" + this.name + " and age:" + this.age);            }        }                  var he = new Child(‘asd‘,12)        console.log(he.firstName)   // qiao        console.log(he.name)    // sad        console.log(he.age)     // 12        he.say()                // name:undefined and age:12

 

這樣書寫就可以繼承name了

 

利用call可以這樣書寫

    var Child = function (name,age) {            Father.call(this,name)            this.age = age            this.say = function(){                console.log(‘i am ‘ + name +‘and age ‘+ age )            }        }  

 

利用apply的話會更加巧妙一點,不用管參數是什麼

      var Child = function (name,age) {            Father.apply(this,arguments)            this.age = age            this.say = function(){                console.log(‘i am ‘ + name +‘and age ‘+ age )            }        }  

 

js 實現繼承

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.