標籤:繼承 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 實現繼承