栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript 'Arrow Functions' and 'Functions'是否等效/可互换?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript 'Arrow Functions' and 'Functions'是否等效/可互换?

tl; dr: 不! 箭头函数和函数声明/表达式不等效,不能盲目替换。
如果要替换的函数 使用

this
arguments
并且 使用调用
new
,则为是。


如此频繁: 这取决于 。箭头函数与函数声明/表达式的行为不同,因此让我们首先看一下它们的区别:

1.词法

this
arguments

箭头函数没有自己的函数

this
或没有
arguments
约束力。相反,这些标识符像任何其他变量一样在词法范围内解析。这意味着,一个箭头函数内部,
this
并且
arguments
指的值
this
arguments
在箭头功能环境
定义 中(即,“外”的箭头功能):

// Example using a function expressionfunction 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 functionfunction 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
。在箭头功能的情况下,
this
指的
this
createObject
自身。

如果需要访问

this
当前环境,这将使箭头功能有用:

// currently common patternvar that = this;getData(function(data) {  that.data = data;});// better alternative with arrow functionsgetData(data => {  this.data = data;});

请注意 ,这也意味着 无法

this
通过
.bind
或设置箭头功能
.call

2.不能使用调用箭头功能

new

ES2015区分了可 调用的 功能和可 构造的 功能。如果一个函数是可构造的,则可以使用调用它

new
,即
newUser()
。如果一个函数是可调用的,则可以不进行调用
new
(即正常函数调用)。

通过函数声明/表达式创建的函数是可构造的和可调用的。
箭头函数(和方法)仅可调用。

class
构造函数只能构造。

如果试图调用不可调用函数或构造不可构造函数,则会出现运行时错误。


知道了这一点,我们可以陈述以下内容。

可更换的:

  • 不使用
    this
    或的函数
    arguments
  • 用于的功能
    .bind(this)

不可 更换:

  • 构造函数
  • 添加到原型的函数/方法(因为它们通常使用
    this
  • 可变函数(如果使用)
    arguments
    (请参阅下文)

让我们使用您的示例仔细看一下:

构造函数

这将无法使用,因为无法使用调用箭头功能

new
。继续使用函数声明/表达式或使用
class

原型方法

很有可能没有,因为原型方法通常用于

this
访问实例。如果他们不使用
this
,则可以替换它。但是,如果您主要关注简洁语法,请使用
class
其简洁方法语法:

class User {  constructor(name) {    this.name = name;  }  getName() {    return this.name;  }}

对象方法

与对象文字中的方法类似。如果方法要通过引用对象本身

this
,请继续使用函数表达式,或使用新的方法语法:

const obj = {  getName() {    // ...  },};

Callbacks

这取决于。如果要别名外部

this
或正在使用,则绝对应该替换它
.bind(this)

// oldsetTimeout(function() {  // ...}.bind(this), 500);// newsetTimeout(() => {  // ...}, 500);

但是: 如果调用回调的代码显式设置

this
为特定值(如事件处理程序,尤其是jQuery),并且回调使用
this
(或
arguments
),
则不能 使用箭头函数!

可变函数

由于箭头函数没有自己的功能

arguments
,因此不能简单地用箭头函数替换它们。但是,ES2015引入了替代方法
arguments
:rest参数。

// oldfunction sum() {  let args = [].slice.call(arguments);  // ...}// newconst sum = (...args) => {  // ...};


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/393943.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号