nameFunction(){}和nameFunction()=>之间的区别{}在ECMA6中 [英] Difference between nameFunction() {} and nameFunction () => {} in ECMA6

查看:90
本文介绍了nameFunction(){}和nameFunction()=>之间的区别{}在ECMA6中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Vue.js和ECMA6语法,我在本教程中看到了这一点:

I'm start learning Vue.js and ECMA6 syntax, I saw this in the tutorial:

methods: {
  someMethod: function() { 
    console.log(this) // this works
  }
} 

然后我认为语法可能是:

Then I thought the syntax could be:

methods: {
  someMethod: () => {
    console.log(this) // this undefined
  }
}

但这可行:

methods: {
  someMethod () {
    console.log(this) // this works
  }
}

能解释一下区别和ECMA5语法吗?

Can explain the difference and the ECMA5 syntax?

推荐答案

ES5中仅支持第一个选项.另外两个是ES6中的新增功能.

Of your three options, only the first one is supported in ES5. The other two are additions in ES6.

第三个选项是第一个选项的ES6快捷方式,因此它们在ES6中的工作方式相同.

The third option is an ES6 shortcut for the first option and thus they work identically in ES6.

在第二个箭头中使用箭头语法时,this不会像在第一个和第三个中一样被设置为宿主对象.这是箭头语法的功能之一,因此当您希望将this设置为宿主对象时,不应使用它.取而代之的是,将this设置为定义代码的词法上下文-通常称为封闭上下文中this的值"或此词法的值",在您的情况下为this是最初声明宿主对象的时间,显然是undefined.

When you use the arrow syntax as in the second one, this is NOT set to be the host object as it is in your first and third. That's one of the features of the arrow syntax and thus it should not be used when you expect this to be set to the host object. Instead, this will be set to the lexical context from where the code was defined - often referred to as "the value of this in the enclosing context" or the "lexical value of this" which in your case would be whatever this was when the host object was initially declared which apparently was undefined.

关于箭头函数,这里有一篇不错的参考文章: ES6深入:箭头函数

Here's a good reference article on arrow functions: ES6 In Depth: Arrow functions

这篇关于nameFunction(){}和nameFunction()=>之间的区别{}在ECMA6中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆