草庐IT

javascript - 'Arrow Functions' 和 'Functions' 是否等效/可互换?

coder 2023-04-23 原文

ES2015 中的箭头函数提供了更简洁的语法。

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

  • 例子:

    构造函数
    function User(name) {
      this.name = name;
    }
    
    // vs
    
    const User = name => {
      this.name = name;
    };
    

    原型(prototype)方法
    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) => {
      // ...
    };
    

    最佳答案

    tl;博士: 不! 箭头函数和函数声明/表达式不是等价的,不能盲目替换。
    如果要替换的函数不使用this , arguments并且不是用 new 调用的, 好的。

    像往常一样:看情况 .箭头函数与函数声明/表达式有不同的行为,所以让我们先看看它们的区别:
    1.词法thisarguments
    箭头函数没有自己的 thisarguments捆绑。相反,这些标识符像任何其他变量一样在词法范围内解析。这意味着在箭头函数内部,thisarguments引用 this 的值和 arguments在环境中,箭头函数定义在(即箭头函数的“外部”):

    // Example using a function expression
    function createObject() {
      console.log('Inside `createObject`:', this.foo);
      return {
        foo: 42,
        bar: function() {
          console.log('Inside `bar`:', this.foo);
        },
      };
    }
    
    createObject.call({foo: 21}).bar(); // override `this` inside createObject



    // Example using a arrow function
    function createObject() {
      console.log('Inside `createObject`:', this.foo);
      return {
        foo: 42,
        bar: () => console.log('Inside `bar`:', this.foo),
      };
    }
    
    createObject.call({foo: 21}).bar(); // override `this` inside createObject

    在函数表达式的情况下,this指的是在 createObject 中创建的对象.在箭头函数的情况下,thisthiscreateObject本身。
    如果您需要访问 this,这使得箭头函数很有用。当前环境:
    // currently common pattern
    var that = this;
    getData(function(data) {
      that.data = data;
    });
    
    // better alternative with arrow functions
    getData(data => {
      this.data = data;
    });
    
    备注 这也意味着无法设置箭头函数的 this.bind.call .
    如果您不是很熟悉 this ,考虑阅读
  • MDN - this
  • YDKJS - this & Object prototypes

  • 2.箭头函数不能用new调用
    ES2015 区分了可调用函数和可构造函数。如果函数是可构造的,则可以使用 new 调用它,即 new User() .如果一个函数是可调用的,它可以在没有 new 的情况下被调用(即正常的函数调用)。
    通过函数声明/表达式创建的函数既可构造又可调用。
    箭头函数(和方法)只能调用。class构造函数只能构造。
    如果您尝试调用不可调用的函数或构造不可构造的函数,则会出现运行时错误。

    知道了这一点,我们可以陈述以下内容。
    可更换:
  • 不使用的函数 thisarguments .
  • .bind(this) 一起使用的函数

  • 不可更换:
  • 构造函数
  • 添加到原型(prototype)的函数/方法(因为它们通常使用 this )
  • 可变函数(如果他们使用 arguments(见下文))
  • 生成器函数,需要 function*符号

  • 让我们用你的例子仔细看看这个:
    构造函数
    这将不起作用,因为无法使用 new 调用箭头函数.继续使用函数声明/表达式或使用 class .
    原型(prototype)方法
    很可能不是,因为原型(prototype)方法通常使用 this访问实例。如果他们不使用 this ,然后就可以更换了。但是,如果您主要关心简洁的语法,请使用 class以其简洁的方法语法:
    class User {
      constructor(name) {
        this.name = name;
      }
      
      getName() {
        return this.name;
      }
    }
    
    对象方法
    对于对象字面量中的方法也是如此。如果该方法想要通过 this 引用对象本身,继续使用函数表达式,或使用新的方法语法:
    const obj = {
      getName() {
        // ...
      },
    };
    
    回电
    这取决于。如果您为外部 this 取别名,您一定要更换它。或正在使用 .bind(this) :
    // old
    setTimeout(function() {
      // ...
    }.bind(this), 500);
    
    // new
    setTimeout(() => {
      // ...
    }, 500);
    
    但是:如果调用回调的代码显式设置 this到一个特定的值,这是事件处理程序的常见情况,尤其是 jQuery,并且回调使用 this (或 arguments ),您不能使用箭头功能!
    可变函数
    由于箭头函数没有自己的 arguments ,您不能简单地用箭头函数替换它们。但是,ES2015 引入了使用 arguments 的替代方法。 : rest parameter .
    // old
    function sum() {
      let args = [].slice.call(arguments);
      // ...
    }
    
    // new
    const sum = (...args) => {
      // ...
    };
    

    相关问题:
  • When should I use arrow functions in ECMAScript 6?
  • Do ES6 arrow functions have their own arguments or not?
  • What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?
  • How to use arrow functions (public class fields) as class methods?

  • 更多资源:
  • MDN - Arrow functions
  • YDKJS - Arrow functions
  • 关于javascript - 'Arrow Functions' 和 'Functions' 是否等效/可互换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361379/

    有关javascript - 'Arrow Functions' 和 'Functions' 是否等效/可互换?的更多相关文章

    1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

      我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

    2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

      我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

    3. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

      给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

    4. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

      我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

    5. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

      我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

    6. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

      在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

    7. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

      我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

    8. ruby - 检查数组是否在增加 - 2

      这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

    9. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

      我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

    10. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

      我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

    随机推荐