九州編程
2019-02-18 13:12:16
function people(word){ this.word = word; this.say = function(){ console.log(this.word); } this.capacity = function(){ return this.say; } } var p = new people('Hello World'); var res = p.capacity(); console.log(res)//? (){console.log(this.word);} console.log(res())//undefined如上帶嗎,我new了一個(gè)people,返回的res 是一個(gè)function但是為什么 我執(zhí)行這個(gè)res為undefined,求解,我想的應(yīng)該打印出來 hello world如果改成這樣呢function people(word){this.word = word;this.say = function(){ console.log(this.word);}()this.capacity = function(){ return this.say;}}var p = new people('Hello World');var res = p.capacity(); //undefined為什么res是undefined
1 回答

jeck貓
TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
好像回答的很晚。你return一個(gè)this.say,而this.say在this.capacity中構(gòu)成了一個(gè)嵌套函數(shù),而在js里嵌套函數(shù)中this是指向window,window中沒有window.word,所以為undefined。
我認(rèn)為把this保存在that里即可:
function people(word){
var that=this;
this.word = word;
this.say = function(){
console.log(that.word);
}
this.capacity = function(){
return this.say;
}
}
添加回答
舉報(bào)
0/150
提交
取消