不正确的引用 this

简介: 不正确的引用 this

随着JavaScript编码技术和设计模式多年来变得越来越复杂,回调和闭包中的自引用作用域也相应增加,这是造成JavaScript问题的 "this/that 混乱 "的一个相当普遍的来源。

考虑下面代码:

Game.prototype.restart = function () {
    this.clearLocalStorage();
    this.timer = setTimeout(function() {
    this.clearBoard();    // What is "this"?
    }, 0);
};

执行上述代码会出现以下错误:

Uncaught TypeError: undefined is not a function

上述错误的原因是,当调用 setTimeout()时,实际上是在调用 window.setTimeout()。因此,传递给setTimeout()的匿名函数是在window对象的上下文中定义的,它没有clearBoard()方法。


传统的、符合老式浏览器的解决方案是将 this 引用保存在一个变量中,然后可以被闭包继承,如下所示:

Game.prototype.restart = function () {
    this.clearLocalStorage();
    var self = this;   // Save reference to 'this', while it's still this!
    this.timer = setTimeout(function(){
    self.clearBoard();    // Oh OK, I do know who 'self' is!
    }, 0);
};

另外,在较新的浏览器中,可以使用bind()方法来传入适当的引用:

Game.prototype.restart = function () {
    this.clearLocalStorage();
    this.timer = setTimeout(this.reset.bind(this), 0);  // Bind to 'this'
};
 
Game.prototype.reset = function(){
    this.clearBoard();    // Ahhh, back in the context of the right 'this'!
};
相关文章
|
9月前
|
存储 编译器 C语言
初谈C++:引用-1
初谈C++:引用
73 0
|
存储 前端开发 rax
【C++】C++引用(上)
【C++】C++引用(上)
|
存储 安全 编译器
【C++】C++引用(下)
【C++】C++引用(下)
|
C++
C++ 中的引用
# C++引用 > 引用是C++新增的复合类型,引用是已定义变量的别名。 - 引用的用途:做函数的形参和返回值。 ## 引用的语法 ```c 引用类型 & 引用名 = 原变量名 ``` **案例** ```c++ #include<cstdio> #include<iostream> using namespace std; void swap(int&a,int&b) //通过引用交换数值 { int tmp = a; a = b; b = tmp; } int main() {
72 0
|
8月前
|
C++
C++引用
C++引用
|
8月前
|
安全 测试技术 C++
C++中的引用
C++中的引用
45 1
|
9月前
|
存储 程序员 C语言
|
9月前
|
存储 安全 编译器
【c++】引用
【c++】引用
【c++】引用
|
编译器 C语言 C++
[C++: 引用】(一)
[C++: 引用】(一)
55 0
|
人工智能 安全 编译器
[C++: 引用】(二)
[C++: 引用】(二)
104 0