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了一个people,返回的res 是一个function但是为什么 我执行这个res为undefined,求解,我想的应该打印出来 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贡献1909条经验 获得超7个赞
好像回答的很晚。你return一个this.say,而this.say在this.capacity中构成了一个嵌套函数,而在js里嵌套函数中this是指向window,window中没有window.word,所以为undefined。
我认为把this保存在that里即可:
function people(word){
var that=this;
this.word = word;
this.say = function(){
console.log(that.word);
}
this.capacity = function(){
return this.say;
}
}
添加回答
举报
0/150
提交
取消