Icon

Littleor

1031 分类: 前端,后端

JS中this到底指向了哪里?

This

JS中的this到底是什么

如果没有系统了解过,可能JavaScript中的this一直是个迷。

可能你在Vue中见过无数这样类似const that = this;的表达式

const that = this;
const obj = {
    message: "I'm obj.",
    printThis: function(){
        console.log(this);
    },
     printThat: function(){
        console.log(that);
    },
};
obj.printThis();
obj.printThat();

这里为什么一定要使用const that = this;呢才能拿到正确的this呢?

是这样的,对于函数(也就是个对象)中的this,指向的是调用该函数的对象的。

举个栗子

function printThis(){
    console.log(this);
}
const obj = {
    message: "I'm obj.",
    printThis: printThis
}

printThis();    // 等同于 this.printThis(); 都是在window这个上下文下调用 this指向的是调用函数的对象: window

obj.printThis();    // 这个printThis是在obj的上下文下调用 this指向的是调用函数的对象: obj

所以可以做个小总结: this总是指向调用本函数(对象)的对象。

而在在构造函数内的this是指向哪里的呢?指向的也是调用构造函数的对象吗?

构造函数会在对象被实例化的时候被调用,会调用call()这个方法来指向该对象,故this指向的是对象本身。具体细节可自行查阅new一个对象的时候做了些什么。

所以就可以回到开始的问题了,为什么要用const that = this;呢?

const that = this;
const obj = {
    message: "I'm obj.",
    printThis: function(){
        console.log(this);
    },
     printThat: function(){
        console.log(that);
    },
};
obj.printThis();
obj.printThat();

其实也就是为了将外部的this保存到that,然后在函数中调用外部的this。

一句话:this就是调用本函数(对象)的对象。

JS中如何优雅的使用this

综合上述,想必应该大概了解了this是什么了。使用const that = this;这种语句肯定不优雅,那么在项目中如何优雅的来使用this呢?

箭头函数

首先可以通过箭头函数来直接使用this,因为箭头函数是不会绑定指针域的,也就是说箭头函数内的this和箭头函数外层的this是一样的。

console.log(this);  // 1 这里指向window
const obj = {
    message: "I'm obj.",
    printThis: function(){
        console.log(this);
    },
    printThisWithArrowFunction: () => { console.log(this); }
}
obj.printThis();    // 2 这里指向 obj
obj.printThisWithArrowFunction();   // 3 这里和1一样指向window

所以可以通过箭头函数来很愉快的解决this指向不同问题。

手动改变函数的this

JS中函数提供了三个方法来手动设定this的指向:call()apply()bind()

通过调用这三个方法来间接调用函数就可以直接指定this,那为什么就指定this需要三个方法呢?

方法 参数 返回值 说明
call() this, param1, param2, ... undefined 传入this指向和参数即可调用
apply() this,[param1, param2, ...] undefined 传入this指向和数组形参数即可调用
bind() this, param1, param2, ... Function 传入this指向和参数返回对应指向的函数

很容易可以发现,三个函数的作用几乎是一样的,但是用法上稍有不同,举个栗子:

function printThis(a, b){
    console.log(this, a, b);
}
const obj = {
    message: "I'm obj."
}
printThis.call(obj, 1, 2);
printThis.apply(obj, [1, 2]);   // 数组形式
printThis.bind(obj, 1, 2)();    // 注意返回的是函数,还需要调用下返回值

更多

想必到现在应该对如何合理使用this大概理解了吧?那么有什么用处呢?

这里拿大家都知道的数组裁剪举个栗子:

const arr = [1, 2, 3];
arr.slice(1); // 去除第一个 这里的slice内部的 this 就指向的是arr!
console.log(arr);   // [2, 3]
// 那么如何利用这个特性来将非一般数组类型切割呢?
const obj = {
    0: 1,
    1: 2,
    2: 3,
    length: 3 // 一定要有length属性
};
// 直接调用 obj.slice(1); 是不可以的因为对象的prototype没有这个方法
// 可以通过人为改变slice的this指针来实现
console.log(Array.prototype.slice.call(obj));   // 使用call方法将this指向了obj即可

#JavaScript

作者: Littleor

版权: 除特别声明,均采用BY-NC-SA 4.0许可协议,转载请表明出处

目录Content

评论