new 关键字 return funciton 问题

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


九州编程
浏览 379回答 1
1回答

jeck猫

好像回答的很晚。你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;    }  }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript