It is really confusing to me that you can call a function in so many different ways. Let me explain.
When you start a project or work on already existing one you want your code to be of the highest quality so other developers may work on it with ease in the future. However there are so many different ways to create a project and you if you're not experienced you may make a big mess.
Let me show you some examples of functions and how you can call them, to show you what I mean.
Example 1: You can just declare a normal function and then call it by name:
function exampleFunc1(){
console.log("hello 1");
}
exampleFunc1(); //hello 1
Example 2: You can also create function expression inside an object:
var mysteriousObject1 = {
example2: function(){
console.log("hello 2");
}
}
mysteriousObject1.example2(); //hello 2
Example 3: or a function declaration inside a function:
function mysteriousObject2() {
function decl() {
console.log("hello 3");
}
decl();
}
mysteriousObject2(); //hello 3
Example 4: You can also call it this way as an anonymous function:
var example4 = function() {
console.log("hello 4");
};
example4(); //hello 4
Example 5: Or even this way:
function exampleFunc5() {
function example5() {
console.log("hello 5");
}
return {
example5: example5
};
}
var call = exampleFunc5();
call.example5(); //hello 5
Example 6: You can also create a class and call a function this way
class User {
constructor(name) {
this.name = name;
}
helloWorld() {
console.log('hello ' + this.name);
}
}
let user = new User("JavaScript");
user.helloWorld(); //hello JavaScript
There are just too many ways and I don't know which approach should I use.
I generally use already existing approach in projects I work on, but which one is the best?
- How to write code to make it easily accessible for other developers in the future?
Thanks for answers.