且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript对象中不同的函数声明之间有什么区别(如果有)?

更新时间:2023-11-29 16:57:58

类样式函数"(速记方法)与常规函数非常相似.唯一的区别是它不能用作构造函数(即用 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.