JavaScript对象中不同的函数声明之间有什么区别(如果有)? [英] What is the difference (if any) between the different function declarations within JavaScript objects?

查看:37
本文介绍了JavaScript对象中不同的函数声明之间有什么区别(如果有)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript对象:

I have a JavaScript object:

var methods = {

  classStyle() {
    console.log('Class style function');
  },

  traditionalStyle: function() {
    console.log('Traditional style function');
  },

  arrowStyle: () => {
    console.log('Arrow style function');
  }

};

methods.classStyle();
methods.traditionalStyle();
methods.arrowStyle();

输出符合预期:

(index):70 Class style function
(index):74 Traditional style function
(index):78 Arrow style function

我的问题是:

  1. 这些不同的声明方法之间根本没有区别吗?
  2. 这是否取决于个人喜好?还是内部工作方式发生了变化?
  3. 使用不同样式时是否需要考虑其他因素?

推荐答案

类样式函数"(速记方法)与常规函数非常相似.唯一的区别是它不能用作构造函数(即用 new 调用),因此它没有 prototype 属性.关于箭头函数,请参见箭头函数与函数声明/表达式:它们是否等效/可以互换?.简而言之,箭头函数不会绑定它们自己的 this arguments ,并且不能与 new 一起使用.

The "class style function" (shorthand method) is very similar to a regular function. The only difference is that it can't be used as a constructor (i.e. called with new), and because of that it doesn't have a prototype property. As for arrow functions, see Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?. In a nutshell, arrow functions don't bind their own this and arguments, and can't be used with new.

这是否取决于个人喜好?还是内部工作方式发生了变化?

Is it down to personal preference? Or do the inner workings change?

在ES6 +中,没有理由在对象中使用传统的函数语法,因为速记方法语法更简单,更安全,因为如果您不小心尝试将方法用作构造函数,则会出错.至于箭头功能,仅当不需要使用 this 访问对象时,才可以使用它们.

In ES6+ there's no reason to use the traditional function syntax in objects, because the shorthand methods syntax is simpler and safer, because if you accidentally try to use a method as a constructor, you'll get an error. As for arrow functions, you can use them only if you don't need to access the object using this.

这篇关于JavaScript对象中不同的函数声明之间有什么区别(如果有)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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