鍍金池/ 問答/HTML/ 關于prototype內方法的執(zhí)行

關于prototype內方法的執(zhí)行

function Animal(name) {
    this.name = name
    
    this._init()
    this._add()
}
Animal.prototype._init = function() {
    this.food = []
    console.log(this.food)
}
Animal.prototype._add = function() {
    console.log(1)
    this.food.push('fish')
    this.food.push('mouse')
    console.log(2)
}

var a = new Animal('cat')

執(zhí)行結果為:

clipboard.png

我的問題是:_add方法在_init方法后執(zhí)行,為什么輸出this.food的時候已經(jīng)被賦值?想不明白,希望有人幫助我理解下b( ̄▽ ̄)d,感謝!

回答
編輯回答
離魂曲

對象是引用類型

2017年7月17日 07:58
編輯回答
毀與悔
function Animal(name) {
    this.name = name

    this._init()
    this._add()
}
Animal.prototype._init = function() {
    this.food = []
    console.log(this.food.toString())//轉換為基礎類型
}
Animal.prototype._add = function() {
    console.log(1)
    this.food.push('fish')
    this.food.push('mouse')
    console.log(2)
    console.log(this.food.toString())//轉換為基礎類型
}

var a = new Animal('cat')

這樣就清楚了,和執(zhí)行順序沒關系,你點開的時候,點的是一個引用。

2018年7月1日 16:47