About the execution of methods in 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")

execution result:

clipboard.png

my question is: the _ add method executes after the _ init method. Why is the output this.food already assigned? I don"t understand. I hope someone can help me understand b. Thank you!

Mar.02,2021

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')

this makes it clear that it has nothing to do with the order of execution. When you click on it, you click on a reference.


object is a reference type

Menu