Trying to clarify this javascript code

So, I am working on some code right now, and there is this code that I am trying to understand. I read a little about this, and it seems that the code uses object literals. So here is the code.

var car = function(){ // ... function drive(model, color){ // ... do something } // ... return { start: drive } }(); 

Called in another file elsewhere

 car.start(audi, black); 

So how does it work. At first it seems that in javascript, a class can have a return method, not just a method. Also does the return method call the? using object literals? I am a bit confused.

+4
source share
3 answers

This is an encapsulation pattern.

  • Objects There are no classes in Javascript, only objects. car contains an object with the structure visible in the return .
  • Functions The external function is anonymous (without a name) and is directly called after the definition (brackets at the end).
  • Local area . The drive function exists only in the environment. You cannot call drive from the outside.
  • Encapsulation . Using the return statement, you can control which functionality will be available externally and how it will be tagged. Therefore, car is an object with one attribute named start , which is the definition of the drive function.

If you call car.start without parentheses, you yourself get the definition of the function:

 function (model, color) { ... } 

This is because functions can be assigned to variables (first-class) without actually calling them so that you can later call predefined functions with the scope of your choice.

If you call car.start(audi, black) , you execute the function with the given parameters and get what is returned by the drive function.

+2
source

At first it seems like in javascript class

JavaScript has no classes. The closest they have to them is the constructor functions, but you don’t have them.

So how does it work

car is the return value of an anonymous function that is called as soon as it is defined (after closing } it has () ).

This return value is an object created using the object literal.

The value of the start property of this object literal is the drive function. Functions are first-class objects in JavaScript, so they can be passed in the same way as any other object.

+3
source

From what looks like creating a car object, you call the disk function from another file and pass the values ​​audi and black through the variable model and color. Then you return an instance of the object ("start") with the variables and actions inside it.

+1
source

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


All Articles