首页 > 有人能不能详细的介绍一下coffeescript种的=> 这个函数绑定符号的使用细节(什么时候使用,怎么用,用的时候注意什么)

有人能不能详细的介绍一下coffeescript种的=> 这个函数绑定符号的使用细节(什么时候使用,怎么用,用的时候注意什么)

如题,如果可以和->进行对比说明更好


看看这段 coffee

coffeescripttest -> 
    this.go()
    inner => 
        this.go();

翻译成 JavaScript 是这样

javascripttest(function() {
    this.go();
    return inner((function(_this) {
        return function() {
            return _this.go();
        };
    })(this));
});

仔细观察你会发现,区别就在于 this 的引用,-> 有独立的 context,但 => 没有。
其实这就是 ES6 的 Lambda(箭头操作符) 在 Coffee 中的实现。

来个有用点的例子

coffeescripttest = () -> 
    this.hello = "hello "
    [1,2,3].forEach((n) =>
        console.log(this.hello, n))
test()

翻译出来

javascriptvar test;

test = function() {
    this.hello = "hello ";
    return [1, 2, 3].forEach((function(_this) {
        return function(n) {
            return console.log(_this.hello, n);
        };
    })(this));
};

test();

结果

VM985:8 hello  1
VM985:8 hello  2
VM985:8 hello  3
【热门文章】
【热门文章】