关于prototype内方法的执行

新手上路,请多包涵
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')

执行结果为:

clipboard.png

我的问题是:_add方法在_init方法后执行,为什么输出this.food的时候已经被赋值?想不明白,希望有人帮助我理解下b( ̄▽ ̄)d,感谢!

阅读 1.7k
2 个回答
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')

这样就清楚了,和执行顺序没关系,你点开的时候,点的是一个引用。

对象是引用类型

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题