关于forEach()第二个参数的问题

clipboard.png

clipboard.png
第一个this指向out我是可以明白的,可是第二个this我就不是很清楚了。不绑定this,console.log(this.name)指向全局。绑定this之后,有点晕了...

阅读 9.9k
4 个回答

实际上在第二个例子中,this的绑定,已经起到了效果,如果没有绑定this,this指向window,但是第二个例子中的this是 obj 而不是 obj.times;

图片描述

图片描述

对于我现在的知识储备来说,有的东西要靠记,你估计也一样
匿名函数的调用者是global/window,记住。。。

print: function() {
    this.times......
    //这个this为什么指向obj,是语言设计者设计的
}
forEach(function(n) {
    console.log(this.name)
}, this)
//如果不绑定this,那这个函数就是一个普通的匿名函数,被作为参数传递给了forEach方法,他的作用域就是window
而绑定的this,其实是print的this,也就是obj,换个写法你看看好不好理解:
var obj = {
    name: 'xx',
    times: [1, 2, 3],
    print: function() {
        var that = this//指向obj;
        this/*指向obj*/.times.forEach(function(n) {
            console.log(this/*原本指向window,被that绑定到obj,*/.name)
        }, that/*前面声明了,此处作为参数传入forEach函数*/)
    }
}

forEach 第一个参数是一个函数,传递进去 this 丢了,指向了全局,使用 forEach 第二个参数来绑定 this 或者使用箭头函数显式的绑定 this 都是可以的。

print: function () {
    this.times.forEach((n) => {
        console.log(this.name)
    })
}
function forEach(calback,contxt){
    let self = this;
    for(let i = 0; i < self.length; i++){
        callback.apply(contxt,self[i]) ----contxt不传是null。指向window
    }    
}
Array.prototype.forEach = forEach;
let obj = {
    id:'awesome'
}
[1,2,3].forEach(function (el){
    console.log(el,this.id)
},obj)

这样你看第二个参数不传他会指向window

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