关于javascript:JS的this指向

6次阅读

共计 790 个字符,预计需要花费 2 分钟才能阅读完成。

对于 this 指向的问题,之前都是只记住,一般函数谁调用,就指向谁,而箭头函数定义在哪个作用域下,this 就指向谁。
然而仿佛这样了解有点通俗。
所以我就傻乎乎的,只记住这一点就去面试了,所以面试官出了这道题,我就 GG 了。

var o = {
    v:'hello',
    p:['a1','a2'],
    f:function f(){this.p.forEach(function(item){console.log(this.v+' '+item);
            console.log('f 中的 this 为:'+this)
        } )
    }
}
o.f()

我的答复是:
hello a1
hello a2
然而实际上是:
undefined a1
undefined a2
我之前的了解是,o.f(), 那就是对象 o 进行调用,那么函数 f 中的 this 就是指向 o, 所以我持续猜测,如果函数外面再定义函数,那么这个外部函数的 this 也可能是指向这个对象 o, 所以导致出错。

所以我公布了这个问答:https://segmentfault.com/q/10…

而后解决了我这个纳闷。所以 this 指向其实记住以下准则就能够了。
(1)一般函数 this 指向是不能确定的,谁调用,this 指向谁;至于没有谁调用的,那么在严格模式下,this 就默认指向 undefined;在非严格模式下就默认指向全局对象;
(2)箭头函数,在哪个中央定义,它就指向哪个对象;
(3)类实质也是函数,外面的 this 都是严格模式下的 this,所以间接获取 this 是会返回 undefined 的,而应用实例获取 this,这个 this 指向的就是实例
对应(3)的例子:

class car{getThis(){return this;}
}
console.log(car.getThis)
var c1 = new car();
console.log(c1.getThis)
console.log(typeof  c1.getThis)

正文完
 0