鍍金池/ 問答/HTML/ new 關鍵字 return funciton 問題

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
但是為什么 我執(zhí)行這個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

回答
編輯回答
澐染

ES5里的this是動態(tài)綁定,也就是說this綁定是函數(shù)的調用位置來決定的,而不是聲明的位置
調用res函數(shù)的時候,res函數(shù)的this指向的是window
想打印hello world直接調用p.say()就是了

2017年1月5日 01:10
編輯回答
巫婆

this箭頭指向問題

2018年1月15日 08:41
編輯回答
青黛色

上下文環(huán)境變了! Javascript 只有「函數(shù)作用域」。
解決辦法:執(zhí)行方法時綁定上下文。
res() 寫成 res.bind(p)() 或 res.apply(p) 或 res.call(p)

2018年1月18日 04:41
編輯回答
念初

你應該return 的是一個結果而不是一個函數(shù),return 函數(shù)的話this的指向會改變,return this.say;相當于把

    function(){
          console.log(this.word);
        }
放在window中了,打印的是window.word,應該為
      function people(word){

this.word = word;
this.say = function(){
   return this.word;
}
this.capacity = function(){
  return this.say();
}

}
var p = new people('Hello World');
var res = p.capacity();
console.log(res);

或者

    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();
2018年7月25日 14:42
編輯回答
命多硬

好像回答的很晚。你return一個this.say,而this.say在this.capacity中構成了一個嵌套函數(shù),而在js里嵌套函數(shù)中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;
    }
  }
2018年8月11日 09:34