彻底掌握JS中的this指向:箭头函数、new、bind、apply和call、对象取值(obj.)、直接调用、不在函数里。按照口诀的顺序,只要满足前面某个场景,就可以确定this指向了。参考文章:理解这7点就能掌握JS中的this指向 (opens new window)
# 作用
call、apply、bind作用是改变函数执行时的上下文,简而言之就是改变函数运行时的this指向。
那么什么情况下需要改变this的指向呢?
var name = 'lucy';
const obj = {
name: 'martin',
say() {
console.log(this.name);
},
};
obj.say(); // martin,this指向obj对象
setTimeout(obj.say, 0); // lucy,this指向window对象
2
3
4
5
6
7
8
9
从上面可以看到,正常情况say方法输出martin。但是我们把say放在setTimeout方法中,在定时器中是作为回调函数来执行的,因此回到主栈执行时是在全局执行上下文的环境中执行的,这时候this指向window,所以输出lucy。我们实际需要的是this指向obj对象,这时候就需要该改变this指向。
setTimeout(obj.say.bind(obj), 0); // martin,this指向obj对象
# 区别
# call
call方法的第一个参数是this的指向,后面传入的是一个参数列表。跟apply一样,改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次。
WARNING
需要注意的是,call和apply指定的this值并不一定是该函数执行时真正的this值,如果这个函数处于非严格模式下,则指定为null和undefined的this值会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字、字符串、布尔值)的this会指向该原始值的自动包装对象。
function fn(...args) {
console.log(this, args);
}
const obj = {
myname: '张三',
};
// this会变成传入的obj,传入的参数必须是一个数组;
fn.call(obj, 1, 2); // obj [1, 2]
// this指向window
fn(1, 2); // window [1, 2]
2
3
4
5
6
7
8
9
10
11
同样的,当第一个参数为null、undefined的时候,默认指向window(在浏览器中)。
fn.call(null, [1,2]); // this指向window
fn.call(undefined, [1,2]); // this指向window
// 都是输出 window [1, 2]
2
3
# apply
apply接受两个参数,第一个参数是this的指向,第二个参数是函数接受的参数,以数组的形式传入。改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次。
function fn(...args) {
console.log(this, args);
}
const obj = {
myname: '张三',
};
// this会变成传入的obj,传入的参数必须是一个数组
fn.apply(obj, [1, 2]); // obj [1, 2]
// this指向window
fn(1, 2); // window [1, 2]
2
3
4
5
6
7
8
9
10
11
当第一个参数为null、undefined的时候,默认指向window(在浏览器中)。
fn.apply(null, [1,2]); // this指向window
fn.apply(undefined, [1,2]); // this指向window
// 都是输出 window [1, 2]
2
3
# bind
bind方法和call很相似,第一参数也是this的指向,后面传入的也是一个参数列表(但是这个参数列表可以分多次传入)。改变this指向后不会立即执行,而是返回一个永久改变this指向的函数。
第一个参数:调用绑定函数时作为this参数传递给目标函数的值。如果使用new运算符构造绑定函数,则忽略该值。当使用bind在setTimeout中创建一个函数(作为回调提供)时,作为thisArg传递的任何原始值都将转换为object。如果bind函数的参数列表为空,或者第一个参数是null或undefined,执行作用域的this将被视为新函数的this。
function fn(...args) {
console.log(this, args);
}
const obj = {
myname: '张三',
};
const bindFn = fn.bind(obj); // this 也会变成传入的obj ,bind不是立即执行需要执行一次
bindFn(1, 2); // this指向obj 输出 obj [1, 2]
fn(1, 2); // this指向window 输出 window [1, 2]
2
3
4
5
6
7
8
9
10
注意:多次bind时只认第一次bind的值,例如:func.bind(1).bind(2),只有前面的bind生效。
function func() {
console.log(this);
}
func.bind(1).bind(2)(); // Number {1}
2
3
4
5
WARNING
注意:绑定函数(bind函数返回的新函数)不可以再通过apply和call改变其this指向,即当绑定函数调用apply和call改变其this指向时,并不能达到预期
效果。
const obj = {};
function test() {
console.log(this === obj);
}
const testObj = test.bind(obj);
testObj(); // true
const objTest = {
name: '1',
};
// 预期返回false, 但是testObj是个绑定函数,所以不能改变其this指向
testObj.apply(objTest); // true
testObj.call(objTest); // true
2
3
4
5
6
7
8
9
10
11
12
13
14
15
WARNING
在JavaScript中,连续多次调用bind方法,最终函数的this上下文是由第一次调用bind方法的参数决定的。
const obj1 = { name: 'obj1' };
const obj2 = { name: 'obj2' };
const obj3 = { name: 'obj3' };
function getName() {
console.log(this.name);
}
const fn1 = getName.bind(obj1).bind(obj2).bind(obj3);
fn1(); // 输出 "obj1"
2
3
4
5
6
7
8
9
10
# 小结
从上面可以看到,apply、call、bind三者的区别在于:
- 三者都可以改变函数的
this对象指向。 - 三者第一个参数都是
this要指向的对象,如果如果没有这个参数或参数为undefined或null,则默认指向全局window。 - 三者都可以传参,但是
apply是数组,而call是参数列表,且apply和call是一次性传入参数,而bind可以分为多次传入。 bind是返回绑定this之后的函数,apply、call则是立即执行。
# 手动实现call
思路:
- 检查调用
call的对象是否为函数; - 将函数作为传入的
context对象的一个属性,调用该函数; - 调用之后删除该属性。
Function.prototype.myCall = function (context, ...args) {
// 检查调用 call 的对象是否为函数
if (typeof this !== 'function') {
throw new TypeError('this is not a function');
}
const ctx = context || window;
// 将函数作为传入的 context 对象的一个属性,调用该函数
const fn = Symbol();
ctx[fn] = this;
const result = ctx[fn](...args);
// 不要忘了调用之后删除该属性
delete ctx[fn];
return result;
};
2
3
4
5
6
7
8
9
10
11
12
13
14
# 手动实现apply
Function.prototype.myApply = function (context, args) {
// 检查调用apply的对象是否为函数
if (typeof this !== 'function') {
throw new TypeError('this is not a function');
}
const ctx = context || window;
// 将函数作为传入的 context 对象的一个属性,调用该函数
const fn = Symbol();
ctx[fn] = this;
const result = ctx[fn](...args);
// 不要忘了调用之后删除该属性
delete ctx[fn];
return result;
};
2
3
4
5
6
7
8
9
10
11
12
13
14
# 手动实现bind
实现bind的步骤,我们可以分解成为三部分:
修改this指向。
动态传递参数。
// 方式一:只在bind中传递函数参数 fn.bind(obj, 1, 2)(); // 方式二:在bind中传递函数参数,也在返回函数中传递参数 fn.bind(obj, 1)(2);1
2
3
4
5兼容new关键字(返回的新函数可能被当做构造函数调用)。
整体实现代码如下:
Function.prototype.myBind = function (context, ...args) {
// context传入的this指向
// 判断调用对象是否为函数
if (typeof this !== 'function') {
throw new TypeError('this is not a function');
}
const ctx = context || window;
const fToBind = this;
const fNOP = function () { };
// bind生成的新函数
const fBound = function (...arg) {
// new操作时:this.__proto__ === fBound.prototype,因此this instanceof fNOP为true
return fToBind.apply(this instanceof fNOP ? this : ctx, args.concat(arg));
};
if (this.prototype) {
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();
return fBound;
};
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fNOP.prototype = this.prototype用于实现对bind()的调用者的原型链的继承。这里this指向bind()的调用者,因此这使得fNOP.prototype指向调用者的原型对象。假使调用者也有原型链,那么这样新函数就也能继承原函数的原型链。当然,只有在调用者是一个函数时才能成立,因此需先判断this.prototype是否存在。fBound.prototype = new fNOP(),fBound.prototype是fNOP的实例,因此会继承fNOP.prototype,又因为fNOP.prototype和this.prototype指向相同对象,因此实现了原型链上的继承。this instanceof fNOP,实现对新函数调用方式的的判断。当新函数作为一般函数直接调用时,它的this指向函数调用对象,显然this不是fNOP的实例。当新函数作为构造函数调用时,fBound内部存在this.__proto__ === fBound.prototype(具体请参考JavaScript中的new操作符),它的this指向新创建的函数,this instanceof fNOP返回真值,因此保证了作为构造函数时内部的this依旧指向新的对象,而不是bind()操作的对象。
绑定函数也可以使用
new运算符构造,它会表现为目标函数已经被构建完毕了似的。提供的this值会被忽略,但前置参数仍会提供给模拟函数。
MDN标准Polyfill (opens new window)
if (!Function.prototype.bind) (function () {
var ArrayPrototypeSlice = Array.prototype.slice;
Function.prototype.bind = function (otherThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var baseArgs = ArrayPrototypeSlice.call(arguments, 1),
baseArgsLength = baseArgs.length,
fToBind = this,
fNOP = function () { },
fBound = function () {
baseArgs.length = baseArgsLength; // reset to default base arguments
baseArgs.push.apply(baseArgs, arguments);
return fToBind.apply(
fNOP.prototype.isPrototypeOf(this) ? this : otherThis, baseArgs
);
};
if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();
return fBound;
};
})();
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
28
29
30