The property within a function is a function, how to execute it

function animal () {

this.eat = function (){
    console.log("i will eat");
}

}
Why can"t it be executed with the method animal.eat (), but with an instance of var. Do not understand the principle
animal.eat (); / / eat is not a function


because the this of your this.eat points to window, in non-strict mode. So your animal.eat is wrong. You can just run eat (),


1.animal must be run once to execute the contents of the function body

2. Directly call animal (), this, point to window, in browser, point to global in node

3. So to perform an eat, you need to write:

animal()

// equal to window.eat() / global.eat()
eat()
The method of an instance of

4.var is to use animal as a constructor function. In the process of new, the function body content is executed and this, is returned. This can be written as follows:

// thiscat
var cat = new animal()

cat.eat()
Menu