ES6 箭头函数--特性

如果箭头表达式仅仅就是简化了函数的命名,我们为什么要改变原来的习惯而去使用它呢?所以我们需要了解一下箭头函数的特性

箭头函数内部没有constructor方法,也没有prototype,所以不支持new操作。但是它对this的处理与一般的普通函数不一样。箭头函数的 this 始终指向函数定义时的 this,而非执行时。我们通过一个例子来理解:

var o = {
    x : 1,
    func : function() { console.log(this.x) },
    test : function() {
        setTimeout(function() {
            this.func();
        }, 100);
    }
};

o.test(); // TypeError : this.func is not a function

上面的代码会出现错误,因为this的指向从o变为了全局(函数调用中的this都是指向全局的)。

我们需要修改上面的代码如下:

var o = {
    x : 1,
    func : function() { console.log(this.x) },
    test : function() {
        var _this = this;
        setTimeout(function() {
            _this.func(); 
        }, 100);
    }
};

o.test();

通过使用外部事先保存的this就行了。这里就可以利用到箭头函数了,我们刚才说过,箭头函数的 this 始终指向函数定义时的 this,而非执行时。所以我们将上面的代码修改如下:

var o = {
    x : 1,
    func : function() { console.log(this.x) },
    test : function() {
        setTimeout(() => { this.func() }, 100);
    }
};

o.test();

这回this就指向o了。

我们还需要注意一点的就是这个this是不会改变指向对象的,我们知道call和apply可以改变this的指向,但是在箭头函数中是无效的。

var x = 1,
    o = {
        x : 10,
        test : () => this.x
    };

o.test(); // 1
o.test.call(o); // 依然是1
原文地址:https://www.cnblogs.com/lulin1/p/7324131.html