Proper way to format javascript function

Just fast ...

What is the proper way to format a javascript function?

I see it like this:

function doThis(){ } 

and like this:

 doThis = function(){ } 

Or maybe that doesn't matter. Please let me know what is best, or if they both have different reasons or goals.

Greetings

FROM

+6
source share
3 answers

These are two different things, although they both create a function (and assign it to a variable).

 function name () { } 

It is a sign of a function (or "function declaration"). Only a top-level element of the script is allowed or directly as a function element: that is, it is not legal to express a function inside an if or while , etc. All functional operators "rise" to the top of the function (or script), so the following is true:

 a() function a () { alert("a") } 

In the shape of:

 variable = function name () {} // or variable = function () {} 

The keyword of the function is in the context of the expression function: it creates a new object-object, and the resulting object-function (simply "normal value") is assigned to variable . The following are not valid because expression functions are not overridden.

 var b b() // oops, does not evaluate to a function-object yet! b = function b () { alert("b") } 

All that is said, the “right way” is to use an expression formula (“function declaration”) if there is no reason for this.

Happy coding.


See also:

+10
source

There is an important and useful difference between these syntaxes.

Encapsulation

In OOP, it is very useful to use encapsulation, which is a mechanism for restricting access to other objects. The difference between public and private vars / functions in javascript can be formulated as follows:

 function Color(value) { // public variable this.value = value; // get from arguments // private variable var _name = "test"; // public function this.getRandomColor = function( ) { return Math.random() * 0xFFFFFF; } // private function function getNiceColor() { return 0xffcc00; } } 

Public Testing

Public variables and functions are available inside the color instance:

 // create instance of Color var color = new Color(0xFF0000); alert( color.value ); // returns red color alert( color.getRandomColor() ); // returns random color 

Testing Private

Private variables and functions cannot be accessed from the color instance:

 var color = new Color(0x0000FF); alert( color.getNiceColor() ); // error in console; property does not exist, because function is private. alert( color._name ); // error in console; property does not exist, because variable is private. 

Note
It is better to use good prototypes when using public functions, because this encoding method can cause inheritance problems.

+2
source

See the first 10-15 slides from [1], they talk about it

[1] http://ejohn.org/apps/learn/

+1
source

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


All Articles