JavaScript中this指向错误的排查与修复方案

作者:木棉

时间:2026-10-30

浏览:269

本文深入解析JavaScript中this指向错误的常见场景,特别是对象方法作为独立函数调用或回调函数使用时this丢失的问题。通过具体代码示例,详细演示了利用bind方法固定this上下文,以及通过变量保存this引用的两种主流修复方案,帮助开发者避免TypeError错误。

文章目录

this指向错误的典型场景

首先观察如下对象定义:


'use strict'
var jane = {
  name : ‘Jane',
  display : function(){
    retrun 'Person named ' + this.name;
  }
};

此时可以正常调用该方法。


jane.display();

然而,若进行如下调用,则会引发错误:


var func = jane.display;
func()

TypeError: Cannot read property 'name' of undefined

利用bind方法修复this指向

原因在于,此时this的指向已经发生改变。正确的处理方式如下所示:


var func2 = jane.display.bind(jane);
func2()

'Penson named Jane'

回调函数中的this问题与解决方案

所有函数内部都拥有独立的this变量,以下面的forEach用法为例:


var jane = {
  name : 'Jane',
  friends: ['Tarzan', 'Cheeta'],
  sayHiToFriends: function(){
    'use strict';
    this.friends.forEach(function(friend) {
      // 'this' is undefined here
      console.log(this.name + ' says hi to '+ friend);
    });
  }
}  

执行sayHiToFriends方法时,会抛出一个错误:


jane.sayHiToFriends()

TypeError: Cannot read property 'name' of undefined

第一种解决方案:将this保存到另一个变量中。


var jane = {
  name : 'Jane',
  friends: ['Tarzan', 'Cheeta'],
  sayHiToFriends: function(){
    'use strict';
    var that = this;
    this.friends.forEach(function(friend) {
      console.log(that.name + ' says hi to '+ friend);
    });
  }
} 

第二种解决方案:利用forEach的第二个参数,该参数允许为this指定特定值。


var jane = {
  name : 'Jane',
  friends: ['Tarzan', 'Cheeta'],
  sayHiToFriends: function(){
    'use strict';
    this.friends.forEach(function(friend) {
      console.log(this.name + ' says hi to '+ friend);
    }, this);
  }
} 

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章