鍍金池/ 問答/HTML5  C++  HTML/ 函數(shù)內(nèi)的屬性是函數(shù),如何執(zhí)行它

函數(shù)內(nèi)的屬性是函數(shù),如何執(zhí)行它

function animal(){

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

}
為什么不能用animal.eat()的方法去執(zhí)行,而是用var一個實(shí)例,去執(zhí)行。不理解其中原理
animal.eat(); //eat不是一個函數(shù)

回答
編輯回答
久愛她

1.animal要運(yùn)行一次才會執(zhí)行函數(shù)體的內(nèi)容

2.直接調(diào)用animal(),this在瀏覽器中指向window,在node中指向global

3.因此要向執(zhí)行eat需要這么寫:

animal()

// equal to window.eat() / global.eat()
eat()

4.var一個實(shí)例的方法是把a(bǔ)nimal當(dāng)做構(gòu)造器函數(shù)使用,new的過程中會執(zhí)行函數(shù)體內(nèi)容,并返回this,可以這么寫:

// this指向cat
var cat = new animal()

cat.eat()
2018年6月18日 07:23
編輯回答
我以為

因?yàn)槟氵@個this.eat的this 指向的是window,在非嚴(yán)格的模式下面。所以你animal.eat是報(bào)錯的。你直接運(yùn)行eat(),就可以了

2017年3月8日 00:17