[英]What is the difference between different ways to create a function inside javascript object?
What is the difference between method1 and method2 ? method1和method2有什么区别?
let myObject = {
method1: function(x){
console.log(...);
},
method2(x){
console.log(...);
}
}
There is no difference. 没有区别。
method2
is just a shorthand syntax introduced in ES6. method2
只是ES6中引入的简写语法。
Starting with ECMAScript 2015, a shorter syntax for method definitions on objects initializers is introduced.
从ECMAScript 2015开始,引入了对象初始值设定项上方法定义的更短语法。 It is a shorthand for a function assigned to the method's name.
它是分配给方法名称的函数的简写。
Source: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Method_definitions 资料来源: https : //developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Method_definitions
There is no real difference here, as stated in the comments. 如评论中所述,这里没有真正的区别。
It's just a matter of "how do you want to write it". 这只是“你想怎么写它”的问题。
But if you're starting a project, you should choose one way and stick to it, and if the project is already started, try to stick to the way the most used. 但是如果你正在开始一个项目,你应该选择一种方法并坚持下去,如果项目已经开始,那么试着坚持使用最多的方式。 It'll greatly help to read the code easily.
这将非常有助于轻松阅读代码。
Also, if it's about scope or binding, you should have a look here : 此外,如果它是关于范围或绑定,你应该看看这里:
http://2ality.com/2015/02/es6-scoping.html http://2ality.com/2015/02/es6-scoping.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.