本文深入解析 JavaScript 中 this 的指向规则,涵盖直接调用、方法调用、new 调用及箭头函数四种场景。详细阐述 bind、call、apply 对 this 的影响,并结合 ES6 class 特性与 jQuery 回调案例,说明常见陷阱及解决方案。
引言
关于 JavaScript 中 this 的指向问题,尽管已有大量文章进行解释,但仍有不少开发者提出疑问。上周,我们的开发团队连续两人遇到相关问题,导致不得不将前端构建技术交流会延长半小时,专门讨论这一主题。
与许多其他编程语言不同,JavaScript 函数中的 this 并非在定义时确定,而是在调用时确定。换言之,函数的调用方式决定了 this 的指向。
JavaScript 中,普通函数的调用方式主要有三种:直接调用、方法调用和 new 调用。此外,还存在一些特殊调用方式,例如通过 bind() 将函数绑定到对象后再调用,或通过 call()、apply() 进行调用。ES6 引入箭头函数后,其 this 指向机制又有所不同。下文将逐一分析这些情况下的 this 指向。
直接调用与 bind() 的影响
直接调用
直接调用是指通过函数名加括号(函数名(...))的方式调用。此时,函数内部的 this 指向全局对象:在浏览器环境中为 window,在 Node.js 环境中为 global。
来看一个例子:
// 简单兼容浏览器和 NodeJs 的全局对象
const _global = typeof window === "undefined" ? global : window;
function test() {
console.log(this === _global); // true
}
test(); // 直接调用
需要注意的是,直接调用并非仅指在全局作用域下的调用。在任何作用域下,只要通过函数名(...)直接调用函数,均视为直接调用。例如以下代码也是直接调用:
(function(_global) {
// 通过 IIFE 限定作用域
function test() {
console.log(this === _global); // true
}
test(); // 非全局作用域下的直接调用
})(typeof window === "undefined" ? global : window);
bind() 对直接调用的影响
另外需注意 bind() 的影响。Function.prototype.bind() 的作用是将当前函数与指定对象绑定,并返回一个新函数。该新函数无论以何种方式调用,其 this 始终指向绑定的对象。示例如下:
const obj = {};
function test() {
console.log(this === obj);
}
const testObj = test.bind(obj);
test(); // false
testObj(); // true
那么 bind() 具体做了什么?我们可以模拟一个 bind() 来理解它如何影响 this。
const obj = {};
function test() {
console.log(this === obj);
}
// 自定义的函数,模拟 bind() 对 this 的影响
function myBind(func, target) {
return function() {
return func.apply(target, arguments);
};
}
const testObj = myBind(test, obj);
test(); // false
testObj(); // true
从上述示例可见,首先通过闭包保持 target(即绑定的对象),然后在调用原函数时使用 apply 方法指定 this。当然,原生 bind() 的实现可能不同且更高效,但该示例说明了其可行性。
call 和 apply 对 this 的影响
call 和 apply 对 this 的影响
上述示例中使用了 Function.prototype.apply(),类似的方法还有 Function.prototype.call()。具体用法请参考相关文档。不过,这两个方法的第一个参数均用于指定函数运行时 this 的指向。
但使用 apply 和 call 时仍需注意:如果目标函数本身已通过 bind() 绑定了 this 对象,那么 apply 和 call 不会按预期执行。例如:
const obj = {};
function test() {
console.log(this === obj);
}
// 绑定到一个新对象,而不是 obj
const testObj = test.bind({});
test.apply(obj); // true
// 期望 this 是 obj,即输出 true
// 但是因为 testObj 绑定了不是 obj 的对象,所以会输出 false
testObj.apply(obj); // false
由此可见,bind() 对函数的影响深远,使用时需谨慎。
方法调用与常见陷阱
方法调用
方法调用是指通过对象调用其方法函数,形式为 对象.方法函数(...)。此时,函数中的 this 指向调用该方法的对象。但同样需要注意 bind() 的影响。
const obj = {
// 第一种方式,定义对象的时候定义其方法
test() {
console.log(this === obj);
}
};
// 第二种方式,对象定义好之后为其附加一个方法(函数表达式)
obj.test2 = function() {
console.log(this === obj);
};
// 第三种方式和第二种方式原理相同
// 是对象定义好之后为其附加一个方法(函数定义)
function t() {
console.log(this === obj);
}
obj.test3 = t;
// 这也是为对象附加一个方法函数
// 但是这个函数绑定了一个不是 obj 的其它对象
obj.test4 = (function() {
console.log(this === obj);
}).bind({});
obj.test(); // true
obj.test2(); // true
obj.test3(); // true
// 受 bind() 影响,test4 中的 this 指向不是 obj
obj.test4(); // false
这里需注意,后三种方式均为先定义函数,再将其附加给 obj 对象作为其方法。再次强调,函数内部的 this 指向与定义无关,仅受调用方式影响。
方法中 this 指向全局对象的情况
这里指的是在 方法 内部而非 方法调用 时 this 指向全局对象。如果不是因为 bind(),那一定是因为未使用方法调用方式。例如:
const obj = {
test() {
console.log(this === obj);
}
};
const t = obj.test;
t(); // false
t 是 obj 的 test 方法,但 t() 调用时,其 this 指向了全局对象。
特别提出这种情况,是因为常将一个对象方法作为回调传递给某个函数后,发现运行结果与预期不符——这是因为忽略了调用方式对 this 的影响。例如在页面中对某些操作进行封装时容易遇到此问题:
class Handlers {
// 这里 $button 假设是一个指向某个按钮的 jQuery 对象
constructor(data, $button) {
this.data = data;
$button.on("click", this.onButtonClick);
}
onButtonClick(e) {
console.log(this.data);
}
}
const handlers = new Handlers("string data", $("#someButton"));
// 对 #someButton 进行点击操作之后
// 输出 undefined
// 但预期是输出 string data
很显然 this.onButtonClick 作为一个参数传入 on() 之后,事件触发时,是对这个函数进行的直接调用,而不是方法调用,所以其中的 this 会指向全局对象。要解决这个问题有很多种方法
// 这是在 es5 中的解决办法之一
var _this = this;
$button.on("click", function() {
_this.onButtonClick();
});
// 也可以通过 bind() 来解决
$button.on("click", this.onButtonClick.bind(this));
// es6 中可以通过箭头函数来处理,在 jQuery 中慎用
$button.on("click", e => this.onButtonClick(e));
不过请注意,将箭头函数用作 jQuery 回调时需小心函数内对 this 的使用。jQuery 大多数非箭头函数回调中的 this 表示调用目标,因此可以写 $(this).text() 这样的语句;但 jQuery 无法改变箭头函数的 this 指向,同样的语句语义完全不同。
new 调用与 ES6 class
new 调用
在 ES6 之前,每个函数均可作为构造函数,通过 new 调用产生新对象(若函数内无特定返回值)。ES6 改变了这一状态:虽然 class 定义的类用 typeof 运算符得到的仍是 "function",但它不能像普通函数一样直接调用;同时,class 中定义的方法函数也不能当作构造函数用 new 调用。
而在 ES5 中,用 new 调用构造函数会创建一个新对象,其中的 this 指向该新对象。这并无悬念,因为 new 本身就是设计用来创建新对象的。
var data = "Hi"; // 全局变量
function AClass(data) {
this.data = data;
}
var a = new AClass("Hello World");
console.log(a.data); // Hello World
console.log(data); // Hi
var b = new AClass("Hello World");
console.log(a === b); // false
箭头函数中的 this
箭头函数中的 this
先来看看 MDN 上对箭头函数的说明。
An arrow function expression has a shorter syntax than a function expression and does not bind its own this , arguments , super , or new.target . Arrow functions are always anonymous. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
这里已清楚说明,箭头函数没有自己的 this 绑定。箭头函数中使用的 this,其实是直接包含它的那个函数或函数表达式中的 this。例如:
const obj = {
test() {
const arrow = () => {
// 这里的 this 是 test() 中的 this,
// 由 test() 的调用方式决定
console.log(this === obj);
};
arrow();
},
getArrow() {
return () => {
// 这里的 this 是 getArrow() 中的 this,
// 由 getArrow() 的调用方式决定
console.log(this === obj);
};
}
};
obj.test(); // true
const arrow = obj.getArrow();
arrow(); // true
示例中的两个 this 均由箭头函数的直接外层函数(方法)决定,而方法函数中的 this 由其调用方式决定。上例的调用方式均为方法调用,因此 this 均指向方法调用的对象,即 obj。
箭头函数使得在使用闭包时无需过度纠结 this,无需通过 _this 等局部变量临时引用 this 供闭包函数使用。以下展示 Babel 对箭头函数的转译,可能有助于加深理解:
// ES6
const obj = {
getArrow() {
return () => {
console.log(this === obj);
};
}
}
// ES5,由 Babel 转译
var obj = {
getArrow: function getArrow() {
var _this = this;
return function () {
console.log(_this === obj);
};
}
};
另外需注意,箭头函数不能用 new 调用,也不能 bind() 到某个对象(虽然 bind() 方法调用没问题,但不会产生预期效果)。无论何时使用箭头函数,它本身不绑定 this,而是使用直接外层函数(即包含它的最近一层函数或函数表达式)绑定的 this。
以上所述是小编给大家介绍的 JavaScript 中 this 指向问题深度解析,希望对大家有所帮助。如果大家有任何疑问请给我留言,小编会及时回复大家。在此也非常感谢大家对本站网站的支持!