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

阅读 3.1k
4 个回答

ES5里的this是动态绑定,也就是说this绑定是函数的调用位置来决定的,而不是声明的位置
调用res函数的时候,res函数的this指向的是window
想打印hello world直接调用p.say()就是了

上下文环境变了! Javascript 只有「函数作用域」。
解决办法:执行方法时绑定上下文。
res() 写成 res.bind(p)() 或 res.apply(p) 或 res.call(p)

你应该return 的是一个结果而不是一个函数,return 函数的话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();

this箭头指向问题

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题