在 JavaScript 中,this 是一个相对难懂的特殊变量。因为它随处可用,而不仅仅是面向对象的编程中。本文将解释 this 是如何工作的,以及它可能导致问题的地方,并在文章的给出最佳实践。
为了方便理解 this ,最好的方式是根据使用 this 的位置划分三种类型:
我们来看看每个类别。
这是 this 最常用的使用场景,因为 JavaScript 中,以三种不同的角色代表了所有的可调用的结构形式:
在函数中,this 可以理解为一个额外隐含的参数。
在真正函数中,this 的值取决于函数所处的模式:
- function sloppyFunc() {
- console.log(this === window); // true
- }
- sloppyFunc();
- function strictFunc() {
- 'use strict';
- console.log(this === undefined); // true
- }
- strictFunc();
也就是说,这是一个默认值( window 或 undefined )的隐式参数。但是,您可以通过 call() 或者 apply() 来调用函数,并明确的指定 this 的值。
- function func(arg1, arg2) {
- console.log(this); // a
- console.log(arg1); // b
- console.log(arg2); // c
- }
- func.call('a', 'b', 'c'); // (this, arg1, arg2)
- func.apply('a', ['b', 'c']); // (this, arrayWithArgs)
如果你通过 new 操作符来调用函数,则函数将成为构造函数。该操作符创建一个新的对象,并通过 this 把它传递给构造函数:
- var savedThis;
- function Constr() {
- savedThis = this;
- }
- var inst = new Constr();
- console.log(savedThis === inst); // true
new 操作符在 JavaScript 中实现,大致如下( 更精确的实现 稍微复杂一点):
- function newOperator(Constr, arrayWithArgs) {
- var thisValue = Object.create(Constr.prototype);
- Constr.apply(thisValue, arrayWithArgs);
- return thisValue;
- }
在方法中,所有的事情都和传统的面向对象语言类似: this 指向接受对象,即方法被哪个对象调用。
- var obj = {
- method: function() {
- console.log(this === obj); // true
- }
- }
- obj.method();
在浏览器环境中,顶级作用域是全局作用域, this 指向 全局对象 (诸如 window 之类):
- <script>
- console.log(this === window); // true
- </script>
在 Node.js 中,你通常在 模块 (module) 中执行代码。因此,顶级作用域是一个指定模块的作用域(module scope)。
- // `global` (not `window`) refers to global object:
- console.log(Math === global.Math); // true
- // this doesn't refer to the global object:
- console.log(this !== global); // true
- // this refers to a module's exports:
- console.log(this === module.exports); // true
eval() 既可以被直接调用(通过一个真正函数调用),也可以被间接调用(通过另一些方式)。以下是具体解释。
如果 eavl() 被间接调用, this 指向 全局对象 ,在控制台中输入:
- > (0,eval)('this === window')
- true
否者,如果 eval() 被直接调用,那么 this 指向 eval() 所处的执行环境。例如:
- // Real functions
- function sloppyFunc() {
- console.log(eval('this') === window); // true
- }
- sloppyFunc();
- function strictFunc() {
- 'use strict';
- console.log(eval('this') === undefined); // true
- }
- strictFunc();
- // Constructors
- var savedThis;
- function Constr() {
- savedThis = eval('this');
- }
- var inst = new Constr();
- console.log(savedThis === inst); // true
- // Methods
- var obj = {
- method: function() {
- console.log(eval('this') === obj); // true
- }
- }
- obj.method();
这里有 3 个和 this 有关的陷阱值得注意的。 记住,严格模式可以使得每种情况变得正常,因为在真正函数中 this 都会为 undefined ,当出错的时候会收到警告。
如果你调用构造函数却忘记使用了 new 操作符,那么你会意外的调用一个真正函数。因此, this 不会指向正确的值。在松散模式中,this 指向 window ,并且会创建全局变量:
- function Point(x, y) {
- this.x = x;
- this.y = y;
- }
- var p = Point(7, 5); // 我们忘记了 new!
- console.log(p === undefined); // true
- // 全局变量已创建:
- console.log(x); // 7
- console.log(y); // 5
幸好,在严格模式下你会收到一条警告( this === undefined):
- function Point(x, y) {
- 'use strict';
- this.x = x;
- this.y = y;
- }
- var p = Point(7, 5);
- // TypeError: Cannot set property 'x' of undefined
如果你获取的是方法的值(而非调用),你会将方法又转变为函数。调用这个值的结果是一个函数调用,而不是一个方法调用。当你将方法作为函数或方法调用的参数传递时,可能会发生这种情况。真实的例子包括 setTimeout() 和 注册处理程序。我将使用 callIt() 函数同步模拟这个用例:
- /* 与 setTimeout() 和 setImmediate() 类似 */
- function callIt(func) {
- func();
- }
如果你调用一个松散模式下的函数, this 指向全局对象,并且创建全局变量:
- var counter = {
- count: 0,
- // 松散模式下 method
- inc: function() {
- this.count++;
- }
- }
- callIt(counter.inc);
- // 不会:
- console.log(counter.count); // 0
- // 相反,一个全局变量已经被创建
- // (NaN 是 undefined 应用 ++ 后结果):
- console.log(count); // NaN
如果你调用严格模式下的函数,this 为 undefined , 代码也将会无效。但是会收到一个警告。
- var counter = {
- count: 0,
- // 严格模式下 method
- inc: function() {
- 'use strict';
- this.count++;
- }
- }
- callIt(counter.inc);
- // TypeError: Cannot read property 'count' of undefined
- console.log(counter.count);
可以使用 bind() 开解决:
- var counter = {
- count: 0,
- inc: function() {
- this.count++;
- }
- }
- callIt(counter.inc.bind(counter));
- // It worked!
- console.log(counter.count); // 1
bind() 创建一个接受的 this 值为 counter 的新函数。
当你在一个方法中使用一个真正函数时,很容易忘记前者有它自己的 this 值(即使真正的函数中没用显式的使用 this )。 因此,你不能从真正函数中的 this 引用到方法的 this,因为它是被覆盖的。 我们来看一个事情出错的例子:
- var obj = {
- name: 'Jane',
- friends: ['Tarzan', 'Cheeta'],
- loop: function() {
- 'use strict';
- this.friends.forEach(function(friend) {
- console.log(this.name + ' knows ' + friend);
- });
- }
- };
- obj.loop();
- // TypeError: Cannot read property 'name' of undefined
在上面例子中,this.name 失败,原因是函数的 this 为 undefined ,他与 loop() 方法内的 this 并不是同一个 this ,这里有 3 种解决方案。
解决方案 1: that = this。将 this 分配给一个变量,使其不再被覆盖(另一个常用的变量名为 self)再使用它。
- loop: function() {
- 'use strict';
- var that = this;
- this.friends.forEach(function(friend) {
- console.log(that.name + ' knows ' + friend);
- });
- }
解决方案 2:bind()。使用 bind() 来创建一个 this 常指向当前值的函数(在下面这个例子中是:方法的 this)。
- loop: function() {
- 'use strict';
- this.friends.forEach(function(friend) {
- console.log(this.name + ' knows ' + friend);
- }.bind(this));
- }
解决方案 3:forEach 的第二个参数。该方法有第二个参数,它的值作为 this 传递给回调函数。
- loop : function(){
- 'use strict';
- this.friends.forEach(function( friend ){
- console.log( this.name + ' knows ' + friend );
- }, this );
- }
概念上来说,我认为真正函数并不具有它们自己的 this ,并且想到前面提到的解决方案就是保持这种错觉。ECMAScript 6 通过箭头函数来支持保持 this – 函数没有其自己的 this 值。在箭头函数中,你可以无忧无虑的使用 this ,因为不会被覆盖。
- loop: function() {
- 'use strict';
- // forEach 的参数就是箭头函数
- this.friends.forEach(friend = >{
- // 'this' 就是 loop 的 'this'
- console.log(this.name + ' knows ' + friend);
- });
- }
我不喜欢 APIs 中像一些普通函数的参数那样使用 this :
- beforeEach(function () {
- this.addMatchers({
- toBeInRange: function (start, end) {
- ...
- }
- });
- });
箭头函数将一个隐式的参数转变为显式的,使得行为更为明确和兼容。
- beforeEach(api => {
- api.addMatchers({
- toBeInRange(start, end) {
- ...
- }
- });
- });
相关优秀文章推荐:
来源: http://www.css88.com/archives/8685