亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

new 關鍵字 return funciton 問題

new 關鍵字 return funciton 問題

九州編程 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了一個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;

    }

  }


查看完整回答
反對 回復 2019-02-20
  • 1 回答
  • 0 關注
  • 391 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號