简体   繁体   English

在javascript对象中创建函数的不同方法有什么区别?

[英]What is the difference between different ways to create a function inside javascript object?

What is the difference between method1 and method2 ? method1method2有什么区别?

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.

相关问题 这两种在JavaScript函数中利用arguments对象的方式有什么区别? - What is the difference between these two ways to leverage the arguments object in a JavaScript function? JavaScript 中自定义事件处理的不同方式有什么区别? - What is the difference between different ways of Custom event handling in JavaScript? 这两种创建对象文字的不同方式有什么区别 - What is the difference between these two different ways of creating an object literal 用Javascript定义对象方法的两种方式有什么区别? - What is the difference between two ways of defining object methods in Javascript? 这两种用JavaScript编写原型函数的方式有什么区别 - What's the difference between these two ways of writting a prototype function in JavaScript 在 javascript 中导出 function 或 object 有什么区别? - What is the difference between exporting a function or an object in javascript? 这两种创建元素的方法有什么区别? - What is the difference between these two ways to create an element? 函数构造函数对象与对象内部对象之间的javascript区别 - javascript difference between function constructor object and an object inside object 在jQuery选择器中转义方括号的这些不同方法之间有什么区别 - What is the difference between these different ways to escape square brackets inside jQuery selectors 有两种方法可以改变javascript对象的原型,它们之间的区别是什么? - 2 ways to change a javascript object's prototype, what's the difference between them?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM