call和bind的一个问题

var obj = {
    name:"zhang",
    age:"21"
}
var ary = [110,120,130,140];
ary.forEach(function(item,index,input){
    console.log(this) //undefined is not a function
}.call(obj))

为什么这里用call不能改变this值为obj,用bind就行,当然这里不讨论forEach的第二个参数来改变上下文

阅读 2.1k
2 个回答

因为在

function(item,index,input){
    console.log(this) //undefined is not a function
}.call(obj)

时,函数就已经执行了,而你这个函数没有返回值,所以你传给forEach的是undefined

而bind调用会自动的返回一个函数。

call 直接就执行了,bind 是绑定不执行

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