Difference between function declaration and function expression in object literal

Suppose I have an object literal using a method:

const testObj = { method: function() { console.log('declaration'); } } 

the same object with a method defined differently:

 const testObj = { method() { console.log('declaration'); } } 

What is the difference between defining a method field in the two examples above? I know that lifting functions and function declarations can be used before they appear in the code, but when defining a function as an object field, this does not seem to matter.

+5
source share
3 answers

Actually no difference according to MDN

Starting with ECMAScript 2015, shorter syntax for method definitions on object initializers. This is an abbreviation for the function assigned to the method name.

+2
source

This is not a difference. The latter is simply a shorthand syntax for writing the same.

For example, in CSS, you can assign a different border radius for each corner separately: border-top-radius: 5px . The abbreviation will be: border-radius: 5px 5px 5px 10px .

This page will open on MDN for more information about the functions of the method.

Edit: Fixed a typo.

0
source

There is no difference between them. This is just a shorthand for another. From the docs :

Starting with ECMAScript 2015, shorter syntax for method definitions on object initializers. This is an abbreviation for the function assigned to the method name.

The following is the documentation:

Given the following code:

 var obj = { foo: function() { /* code */ }, bar: function() { /* code */ } }; 

Now you can shorten this:

 var obj = { foo() { /* code */ }, bar() { /* code */ } }; 
0
source

Source: https://habr.com/ru/post/1276219/


All Articles