理解js中this的指向

首先必须要说的是,this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象。

情况1:如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window,这里需要说明的是在js的严格版中this指向的不是window,但是我们这里不探讨严格版的问题,你想了解可以自行上网查找。

情况2:如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象。

情况3:如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象,

部分代码如下:

var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = function () {
            console.log(this);  // this指向window或undefined
            return new Date().getFullYear() - this.birth;
        };
        return fn();
    }
};
var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = function () {
            console.log(this);  // 使用bind后this指向obj
            return new Date().getFullYear() - this.birth;
        }.bind(this);
        return fn();
    }
};

参考文章地址1:https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001438565969057627e5435793645b7acaee3b6869d1374000

参考文章地址2:https://www.cnblogs.com/pssp/p/5216085.html

posted @ 2018-12-12 14:57  jim520  阅读(237)  评论(0编辑  收藏  举报