I googled but didn’t find much about something like “function as an object”… how is it called in order to learn more and perhaps a resource explaining more deeply?
nameFunction is a function that returns an object. That object has a property (secFunction) whose value happens to be a function, nothing more. Object properties can have any value: eg primitive values like strings or numbers, or arrays, or other objects, or functions, or whatever.
@Snippet
The first is essentially equivalent to a pre ES6 function and has an advantage over the later anonymous/arrow style ES6 function when it comes to classes and objects, but a disadvantage in the length or for an inline function etc.
The first is closely related to;
const object = {
Color: "black",
Start: function() { alert("the car has started"); }
};
One major disadvantage that using an anonymous or arrow style function has in classes/objects relates to the use of the ‘this’ keyword to refer to the current instance of the class/object.
for instance;
const object = {
Color: "black",
Start: () => alert(`The car is ${this.Color}.`)
};
Would fail and result in an error as it would be unable to resolve ‘this’ (undefined). You can, however, make it work by replacing the ‘this’ keyword with the name of the class/object ( in this case object.Color), but if the name of the class/object were to change then you’d also need to edit every use of the classes/objects name within its definition.
While the above example would fail, this will work as expected;
const object = {
Color: "black",
Start: function() { alert(`The car is ${this.Color}.`); }
};
As would this;
const object = {
Color: "black",
Start() { alert(`The car is ${this.Color}.`); }
};
it’s just shorthand. The shorthand was added at the same time as an additional form of function (arrow functions).
So if you can write
const obj = {
method: function () {
},
}
Then why would there be any reason why you would be prevented from writing
const obj = {
method: () => {
},
}
It depends on context. If you want to use this for a function directly attached to an object, then don’t use an arrow function. For example, what do obj.explain() and obj.noexplain() return?
const obj = {
name: "Simon",
explain: function () {
return `This object is called ${this.name}`;
},
noExplain: () => {
return `This object is called ${this.name}`;
},
}
There are many many many articles about this and scope. Arrow functions solve the issue of wanting, within a function attached to an object, to write functions that refer to the same this without having to use bind.
small detail to note, functions that are object properties are also called methods of that object. secFunction is a method of the object returned by the nameFunction. Its just a term that carries slightly more meaning and when you refer to such functions as methods, this gives out additonal background of their nature.