zoukankan      html  css  js  c++  java
  • Javascript中颇受诟病的「this错乱」问题

    function Countdown(seconds) {
        this._seconds = seconds;
    }
    Countdown.prototype._step = function() {
        console.log(this._seconds);
        if (this._seconds > 0) {
            this._seconds -= 1;
        } else {
            clearInterval(this._timer);
        }
    };
    Countdown.prototype.start = function() {
        this._step();
        this._timer = setInterval(function() {
            this._step();
        }, 1000);
    };
    
    new Countdown(10).start();

    运行这段代码时,将会出现异常「this._step is not a function」。这是Javascript中颇受诟病的「this错乱」问题:setInterval重复执行的函数中的this已经跟外部的this不一致了。要解决这个问题,有三个方法。

    闭包

    新增一个变量指向期望的this,然后将该变量放到闭包中:

    Countdown.prototype.start = function() {
        var self = this;
        this._step();
        this._timer = setInterval(function() {
            self._step();
        }, 1000);
    };

    bind函数

    ES5给函数类型新增的「bind」方法可以改变函数(实际上是返回了一个新的函数)的「this」:

    Countdown.prototype.start = function() {
        this._step();
        this._timer = setInterval(function() {
            this._step();
        }.bind(this), 1000);
    };

    箭头函数

    箭头函数是ES6中新增的语言特性,表面上看,它只是使匿名函数的编码更加简短,但实际上它还隐藏了一个非常重要的细节——箭头函数会捕获其所在上下文的this作为自己的this。也就是说,箭头函数内部与其外部的this是保持一致的。所以,解决方案如下:

    Countdown.prototype.start = function() {
        this._step();
        this._timer = setInterval(() => {
            this._step();
        }, 1000);
    };
  • 相关阅读:
    CSU 1505: 酷酷的单词【字符串】
    HDU 2036 改革春风吹满地【计算几何/叉乘求多边形面积】
    HDU 2034 人见人爱A-B【STL/set】
    HDU 2031 进制转换
    HDU 1020 Encoding【连续的计数器重置】
    HDU 1999 不可摸数【类似筛法求真因子和】
    动态规划总结
    CSU 1785: 又一道简单题
    CSU 1779: 错误的算法【矩阵/模拟】
    CSU 1777: 大还是小?【模拟/后导0】
  • 原文地址:https://www.cnblogs.com/utrustme/p/6941743.html
Copyright © 2011-2022 走看看