代码之家  ›  专栏  ›  技术社区  ›  Scaramouche

使用fat箭头[duplicate]向jQuery原型添加新函数

  •  0
  • Scaramouche  · 技术社区  · 7 年前

    • 现在可以用箭头函数替换所有的函数声明/表达式吗?
    • 我要注意什么?

    构造函数

    function User(name) {
      this.name = name;
    }
    
    // vs
    
    const User = name => {
      this.name = name;
    };
    

    原型方法

    User.prototype.getName = function() {
      return this.name;
    };
    
    // vs
    
    User.prototype.getName = () => this.name;
    

    const obj = {
      getName: function() {
        // ...
      }
    };
    
    // vs
    
    const obj = {
      getName: () => {
        // ...
      }
    };
    

    回拨

    setTimeout(function() {
      // ...
    }, 500);
    
    // vs
    
    setTimeout(() => {
      // ...
    }, 500);
    

    function sum() {
      let args = [].slice.call(arguments);
      // ...
    }
    
    // vs
    const sum = (...args) => {
      // ...
    };
    
    0 回复  |  直到 5 年前