ES.next 的 => 函数语法
发布于 11 年前 作者 jiyinyiyong 5229 次浏览 最后一次编辑是 8 年前

ECMAScript.next: arrow functions and method definitions

翻到 RSS 于是看了一遍, 文章好长, 跳着摘一些重点过来:

动态的 this

原先我们的函数, 会遇到 this 指向不明确的问题, 只好加 bind:

    var jane = {
        name: "Jane",
        
        logHello: function (friends) {
            friends.forEach(function (friend) {
                console.log(this.name + " says hello to " + friend)
            }.bind(this));
        }
    }

词法域的 this

ES6 里的 () => {} 函数定义语法, 就是冲着这个来的:

    let jane = {
        name: "Jane",
        
        logHello: function (friends) {
            friends.forEach(friend => {
                console.log(this.name + " says hello to " + friend)
            });
        }
    }

这里的 this 是词法域的, 因此代码可以按照预期地执行 当然 => 这货是 CoffeeScript 里学去的… 但相比起来, coffee 的 => 大概有些场合还会有问题

更多语法:

        () => { ... } // no argument
         x => { ... } // one argument
    (x, y) => { ... } // several arguments
    let squares = [ 1, 2, 3 ].map(function (x) { return x * x });
    let squares = [ 1, 2, 3 ].map(x => x * x);

这里定义的 => 函数和 JS 通常的函数定义有 3 点不同:

  1. this 永远是被绑定了的
  2. 没有原型链之类功能, 不能用做构造器
  3. arguments 变量不存在

方法的定义

然后… 文章中间讨论了一堆, 没看懂…

另一个提到的是方法定义的语法:

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        // Method definition:
        dist() {
            return Math.sqrt((this.x*this.x)+(this.y*this.y));
        }
    }
    let jane = {
        name: "Jane",
        
        // Method definition:
        logHello(friends) {
            friends.forEach(friend => {
                console.log(this.name + " says hello to " + friend)
            });
        }
    }

也变得很简短了. 只不过括号还是很多… 总之原先旧的写法在 JS 里将会比较少见 因为函数作为构造器, 作为 subroutine 都有了更好的语法


此外

刚看到消息说 Firefox 22 已经部署了 => 语法, 还没去看 https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/22#JavaScript


文章作者说这几个函数的语法让 JS 更简单了… 的确, 从 this 的角度说, 更明确了 从 CoffeeScript 对比看, JS 的函数定义的语法种类在变多… 我个人觉得不大惯

3 回复

看来 =〉只用于定义无名函数。

终于正识到这个问题了,但是这个语法也太摧残了

学 CoffeeScript 学的 --!

回到顶部