秒懂this

项目开发中经常会遇到 this 指向的问题,可能会纠结很久,今天将 this 做个汇总,以便在日后的开发中少走弯路,而且在面试中也可能会被问及。

注意:本文讲述只针对浏览器环境。

一:全局执行

1
2
console.log(this);
//window

可以看出在全局作用域中 this 指向当前的全局对象 Window。

二:函数中执行

1.非严格模式中

1
2
3
4
5
function func() {
console.log(this);
}
func();
// Window

2.严格模式中

1
2
3
4
5
6
"use strict";
function func() {
console.log(this);
}
func();
// undefined

三:作为对象的方法调用

当一个函数被当作一个对象的方法调用的时候,this 指向当前的对象 obj:

1
2
3
4
5
6
7
8
var obj = {
name: "dabao",
func: function () {
console.log(this.name);
},
};
obj.func();
// dabao

如果把对象的方法赋值给一个变量,调用该方法时,this 指向 Window:

1
2
3
4
5
6
7
8
9
var obj = {
name: "dabao",
func: function () {
console.log(this);
},
};
var test = obj.func;
test();
// Window

四:作为一个构造函数使用

在 JS 中,为了实现类,我们需要定义一些构造函数,在调用一个构造函数的时候加上 new 这个关键字:

1
2
3
4
5
6
function Person(name) {
this.name = name;
console.log(this);
}
var p1 = new Person("dabao");
// Person

此时,this 指向这个构造函数调用的时候实例化出来的对象。
当然了,构造函数其实也是一个函数,若将构造函数当做普通函数来调用,this 指向 Window:

1
2
3
4
5
6
function Person(name) {
this.name = name;
console.log(this);
}
var p2 = Person("dabao");
// Window

五:在定时器中使用

1
2
3
4
setInterval(function () {
console.log(this);
}, 2000);
// Window
1
2
3
4
setTimeout(function () {
console.log(this);
}, 0);
// Window

如果没有特殊指向(指向更改请看下方:怎么改变 this 的指向),setInterval 和 setTimeout 的回调函数中 this 的指向都是 Window 。这是因为 JS 的定时器方法是定义在 Window 下的。

六:箭头函数

在全局环境中调用:

1
2
3
4
var func = () => {
console.log(this);
};
func();

作为对象的一个函数调用:

1
2
3
4
5
6
7
8
var obj = {
name: "dabao",
func: function () {
console.log(this);
},
};
obj.func();
// obj
1
2
3
4
5
6
7
8
var obj = {
name: "dabao",
func: () => {
console.log(this);
},
};
obj.func();
// Window

不难发现,普通函数作为对象的一个函数被调用,this 指向 obj,箭头函数作为对象的一个函数被调用,this 指向 Window。

特殊情况:结合定时器调用:

1
2
3
4
5
6
7
8
9
10
var obj = {
name: "dabao",
func: function () {
setTimeout(function () {
console.log(this);
}, 0);
},
};
obj.func();
// Window
1
2
3
4
5
6
7
8
9
10
var obj = {
name: "dabao",
func: function () {
setTimeout(() => {
console.log(this);
}, 0);
},
};
obj.func();
// obj

若在对象的函数中,普通函数作为定时器延时执行的函数调用,this 指向 Window;箭头函数作为定时器延时执行的函数调用, this 指向定义时所在的对象,也就是 func 中的 this,即 obj。

箭头函数中 this 的值取决于该函数外部非箭头函数的 this 的值,且不能通过 call() 、 apply() 和 bind() 方法来改变 this 的值。

七:call、apply、bind

call:

1
fun.call(thisArg[, arg1[, arg2[, ...]]])

它会立即执行函数,第一个参数是指定执行函数中 this 的上下文,后面的参数是执行函数需要传入的参数;

apply:

1
fun.apply(thisArg, [argsArray]);

它也会立即执行函数,第一个参数是指定执行函数中 this 的上下文,第二个参数是一个数组,是传给执行函数的参数(与 call 的区别);
我们来看个示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function Person(name, age) {
this.name = name;
this.age = age;
console.log(this);
}
var obj = {
name: "dabao",
age: 25,
};
Person.call(obj, "xiaoniu", 26);
// obj,{name: "xiaoniu", age: 26}

Person.apply(obj, ["siji", 26]);
// obj,{name: "siji", age: 26}

var p1 = Person.bind(obj, "baojie", 26);
var p2 = new p1();
// Person {name: "baojie", age: 26}

在这个示例中,call、apply 和 bind 的 this 都指向了 obj,都能正常运行;call、apply 会立即执行函数,call 和 apply 的区别就在于传递的参数,call 接收多个参数列表,apply 接收一个包含多个参数的数组;bind 不是立即执行函数,它返回一个函数,需要执行 p2 才能返回结果,bind 接收多个参数列表。

call、apply 有什么区别?call,aplly 和 bind 的内部是如何实现的?

call 和 apply 的功能相同,区别在于传参的方式不一样:
fn.call(obj, arg1, arg2, …), 调用一个函数, 具有一个指定的 this 值和分别地提供的参数 (参数的列表)。
fn.apply(obj, [argsArray]), 调用一个函数,具有一个指定的 this 值,以及作为一个数组(或类数组对象)提供的参数。

call 核心:

将函数设为传入参数的属性;
指定 this 到函数并传入给定参数执行函数;
如果不传入参数或者参数为 null,默认指向为 window / global;
删除参数上的函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Function.prototype.call = function (context) {
/** 如果第一个参数传入的是 null 或者是 undefined, 那么指向 this 指向 window/global */
/** 如果第一个参数传入的不是 null 或者是 undefined, 那么必须是一个对象 */
if (!context) {
//context 为 null 或者是 undefined
context = typeof window === "undefined" ? global : window;
}
context.fn = this; //this 指向的是当前的函数 (Function 的实例)
let args = [...arguments].slice(1); // 获取除了 this 指向对象以外的参数, 空数组 slice 后返回的仍然是空数组
let result = context.fn(...args); // 隐式绑定, 当前函数的 this 指向了 context.
delete context.fn;
return result;
};

// 测试代码
var foo = {
name: "Selina",
};
var name = "Chirs";
function bar(job, age) {
console.log(this.name);
console.log(job, age);
}
bar.call(foo, "programmer", 20);
// Selina programmer 20
bar.call(null, "teacher", 25);
// 浏览器环境: Chirs teacher 25; node 环境: undefined teacher 25

apply

apply 的实现和 call 很类似,但是需要注意他们的参数是不一样的,apply 的第二个参数是数组或类数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Function.prototype.apply = function (context, rest) {
if (!context) {
//context 为 null 或者是 undefined 时, 设置默认值
context = typeof window === "undefined" ? global : window;
}
context.fn = this;
let result = context.fn(...rest);
delete context.fn;
return result;
};
var foo = {
name: "Selina",
};
var name = "Chirs";
function bar(job, age) {
console.log(this.name);
console.log(job, age);
}
bar.apply(foo, ["programmer", 20]);
// Selina programmer 20
bar.apply(null, ["teacher", 25]);
// 浏览器环境: Chirs programmer 20; node 环境: undefined teacher 25

bind

bind 和 call/apply 有一个很重要的区别,一个函数被 call/apply 的时候,会直接调用,但是 bind 会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Function.prototype.bind = function (context) {
if (typeof this !== "function") {
throw new TypeError("not a function");
}
let self = this;
let args = [...arguments].slice(1);
function Fn() {}
Fn.prototype = this.prototype;
let bound = function () {
let res = [...args, ...arguments]; //bind 传递的参数和函数调用时传递的参数拼接
context = this instanceof Fn ? this : context || this;
return self.apply(context, res);
};
// 原型链
bound.prototype = new Fn();
return bound;
};

var name = "Jack";
function person(age, job, gender) {
console.log(this.name, age, job, gender);
}
var Yve = { name: "Yvette" };
let result = person.bind(Yve, 22, "enginner")("female");

应用:怎么改变 this 的指向

为什么讲这个模块呢,为了便于我们更加透彻的理解上面所讲述的 this 指向问题,以及更加彻底的理解 JS 函数中重要的三种方法:call、apply、bind 的使用;并且在实际的项目开发中,我们经常会遇到需要改变 this 指向的情况。

我们来看下都有哪些方法:

1. 使用 es6 的箭头函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var name = "dabao";
var obj = {
name: "jiaru",
func1: function () {
console.log(this.name);
},
func2: function () {
setTimeout(function () {
this.func1();
}, 1000);
},
};

obj.func2();
// Uncaught TypeError: this.func1 is not a function

这时会报错,因为 setTimeout 里函数的 this 指向 Window,而 Window 对象上是没有 func1 这个函数的。下面我们来修改成箭头函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var name = "dabao";
var obj = {
name: "jiaru",
func1: function () {
console.log(this.name);
},
func2: function () {
setTimeout(() => {
this.func1();
}, 1000);
},
};

obj.func2();
// jiaru

这时候,没有报错,因为箭头函数的 this 的值取决于该函数外部非箭头函数的 this 的值,也就是 func2 的 this 的值, 即 obj。

2. 在函数内部使用 _this = this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var name = "dabao";
var obj = {
name: "jiaru",
func1: function () {
console.log(this.name);
},
func2: function () {
var _this = this;
setTimeout(function () {
_this.func1();
}, 1000);
},
};

obj.func2();
// jiaru

此时,func2 也能正常运行。在 func2 中,首先设置 var _this = this,这里的 this 是指向 func2 的对象 obj,为了防止在 func2 中的 setTimeout 被 window 调用而导致的在 setTimeout 中的 this 为 window。我们将 this (指向变量 obj) 赋值给一个变量 _this,这样,在 func2 中我们使用 _this 就是指向对象 obj 了。

3. 使用 call、apply、bind

call:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var name = "dabao";
var obj = {
name: "jiaru",
func1: function () {
console.log(this.name);
},
func2: function () {
setTimeout(
function () {
this.func1();
}.call(obj),
1000
);
},
};

obj.func2();
// jiaru

apply:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var name = "dabao";
var obj = {
name: "jiaru",
func1: function () {
console.log(this.name);
},
func2: function () {
setTimeout(
function () {
this.func1();
}.apply(obj),
1000
);
},
};

obj.func2();
// jiaru

bind:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var name = "dabao";
var obj = {
name: "jiaru",
func1: function () {
console.log(this.name);
},
func2: function () {
setTimeout(
function () {
this.func1();
}.bind(obj)(),
1000
);
},
};

obj.func2();
// jiaru

call、apply、bind 都能改变 this 的上下文对象,所以也没有报错,可以正常执行。
具体原因可看上述第七点。