浏览器 JavaScript 中的 this 的使用【最全总结,值得收藏】

前言

大家可以看上一篇文章,是关于 Nodejs 中 this 的使用,里面还总结了 Nodejs 与浏览器 JavaScript 中的 this 的区别


JavaScript 中 this 的使用

全局下的 this

  • 非严格模式情况下,全局的 this 都是 window

    console.log( this );  // window
    function fn(){
        console.log( this );  // window
    }
    
  • 严格模式下,抑制 this

    禁用指向了 window 的 this,让 this 指向 undefined

    "use strict";
    function foo(){
       console.log(this);  // undefined
    }
    foo()
    

    具体内容原因见:ES5 规范之严格模式详解

对象中的 this

  • 属性描述 this 时,这个时候对象还没有生成,所以 this 指向外层的 this 指向;
  • 对象的方法中 this 是该对象本身
var a = 10;
var obj1 = {
    a: 100,
    c: this.a,  // window,对象当中,this指向window,因为是属性描述,对象还没有生成,所以指向外层this指向
    init: function () {  // 对象的属性函数中,this指向对象obj1
        var obj = {
            a: 1,
            c: this.a,  // 属性描述this,obj1
            b: function () {
                // obj对象的方法中this指向obj对象
                console.log(this.a);  // 1
            }
        }
    }
}  
// 到这里对象算是创建完成
var a = 20;
var obj = {
    a: 1
}
obj.b = {
    a: 100,
    c: this.a,  // 20
    // 创建obj.b.c的时候,obj.b还没创建完成,所以不认为b是obj上的属性,所以this依然指向外层this的指向,也就就是window
    d: function() {
        console.log( this.a );  // 100 this指向本属性
    }
}

console.log( obj.b.c );  // 20
var obj = {
    a: 1,
    b: function() {
        // this -> obj
        var o = {
            // 判定o对象没有创建完,this指当前对象外this的指向,这里的this指向是obj
            c: this.a  // 1
        }
        console.log( o.c );  // 1
    }
}

obj.b();

回调函数的 this

function ab(fn) {
    fn();
}
function cd() {
    // this因为回调函数重定向指向window
    console.log(this);  // window
}

ab(cd);
var obj = {
    a: function(fn){
        fn();
    },
    b: function(){
        // 如果直接执行obj.b() 这里的this应该是obj对象
        // 如果通过上面a方法回调执行当前b的时候,this被重定向到window
        console.log(this);  // window
    }
}

obj.a(obj.b);
// forEach, filter, reduce, some, every, flatMap 等里面都是回调函数都指向 window
var obj = {
    a: function () {
        setTimeout(function () {
            console.log(this)  // window,匿名回调函数
        }, 100);
        // 所有的函数一旦被写在一个方法中,这个函数就是匿名的回调函数,在该函数中this指向window
        setInterval(function(){
            console.log(this);  // window
        },100)
        var arr=[1,2,3];
        arr.map(function(){
            console.log(this);  // window
            // 匿名回调函数
        });
        new Promise(function(resolve,reject){
            console.log(this);  // window
        })
    }
}

事件 this 指向

事件侦听的回调函数是特殊的回调函数,this 是被重新处理了,this 指向被侦听的对象

document.addEventListener("click", clickHandler);

function clickHandler(e) {
    // this === e.currentTarget
}
var obj = {
    a: function(){
        document.addEventListener("click", this.b);  // 点击后触发,打印document
        this.b();  // 直接运行 打印obj对象
    },
    b: function(e){
        // 因为b函数是事件侦听的回调函数,因此这里this指向事件侦听的对象,也就是document
        console.log(this);
    }
}
obj.a();

ES6 中的 this 指向

  • 类中的 this 基本都是指向实例化后的对象,静态的 this 指向类本身
class Box{
    // ES7后才有的
    // 这里的内容是constructor执行后赋值
    b = 3;
    constructor() {
        this.a = this.b;
        Box.b = 20;
        Box.a = Box.b;
        // 之前没有static所以都是上述方式,来静态操作,上下等同
        // static b = 20; 
        // static a = this.b;  // 一旦被设为静态属性,this指向都会被设置为当前的类名Box
    } 
    play(){
        // 这里的this都是实例化的对象
        console.log(this.a);
    }

    static run(){
       console.log(this);
        // this
        // 因为使用static定义的方法,this指向为当前类名Box
        // 对于面向对象语言来说,一般在静态属性和方法中不允许使用this这个概念
    }    
}
// 新建类然后继承
class Ball extends Box{
    constructor() {
        super();
    }
}
var b = new Ball();
Ball.run();  // 这里打印的Ball类,继承会重定向this到新类中

// 继承后静态方法也会被继承
var b = new Box();
console.log( b.a );  // 3
b.play();  // 3
console.log( Box.a );  // 20

Box.run()  // 打印box类

ES6 箭头函数的 this 指向

所有箭头函数内的 this 都是指当前函数外的 this 指向

var fn = () => {

};
var obj = {
    a: () => {
        console.log(this);  // this --> window
    },
    b: function() {
        console.log(this);  // this --> obj
    },
    c() {
        console.log(this);  // this --> obj
    }
}
obj.a();  // window
obj.b();  // obj
obj.c();  // obj
var obj = {
    a: function() {
        setTimeout(() => {
            // 因为本来是回调函数,this统一都会被执行window
            // 但是使用了箭头函数,就会全部把这里this指向setTimeout外的this指向,也就是obj
            console.log(this);  // obj
        }, 100)
    }
}
obj.a();  // obj

ES5 中的 this 指向

因为 ES5 中没有类的方法,所以我们都是如下方式建立一个类

function Box() {  // 构造函数
    this.play();
    // 构造函数中this,new出的对象
}
Box.a = function() {
    // 这个方法类似于ES6的静态方法
    // this --> Box
}
Box.b = 3;  // 和ES6静态定义属性一样
Box.prototype.play = function() {
    // this 就是当前调用该方法的实例对象
}
Box.prototype.c = 10;

console.log(Box.b);  // 3
Box.a();

var b = new Box();
b.play()
// b对象没有play这个对象属性,因此就去原型链中找到最近的play方法,执行这个play方法是由b这个对象执行
console.dir(Box);  // 打印Box类, console.dir()可以显示一个对象的所有属性和方法
  • 因为 box 只是一个函数所以用 console.dir() 打印成为一个类

  • 静态方法只和类有关系,与实例化的对象没有任何关系

当使用 callapplybind 都会将函数中 this 的指向重新指向到对应的对象

之前有详细写过,请移步至:call、apply、bind三者之间的用法和区别,并手写实现


this指向总结

1. 函数的 this 指向

在函数调用的时候决定 this 指向,函数调用的时候,函数的调用者是谁,那么 this 指向就指向谁。

  • 函数调用前没有调用者,调用者默认为 window
  • 函数有调用者,this 指向必然指向调用者
2. 回调函数的 this 指向
  • 事件的 this 指向比较特殊: this => 当前发生事件的元素
  • 其余所有的情况 this 指向都指向 window
3. 构造函数的 this 指向

构造函数内部 this 指向指向实例对象

4. 捷径:所有的面向对象里面的 this 都指向实例对象

那么,原型对象里面即要使用事件的元素又要使用实例对象该怎么办?
可以使用 bindcallapply 来改变 this 的指向。


this 在 Nodejs 中的使用

请移步至:Nodejs 中关于 this 的使用以及与浏览器 JavaScript 中的 this 的区别【亲自踩坑总结,值得收藏】


希望以上内容可以帮助到大家。有任何问题欢迎讨论留言,不要忘记一键三连哦~。

各位 加油!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值