Reputation: 1977
So I'm working on some code right now and there is this code I'm trying to understand. I've read a bit about it and it seems that the code is using 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 this work. First it seems that in javascript a class can have a return method and not just a method. Also the return method is calling a method? using object literals? I'm a bit confused here.
Upvotes: 3
Views: 224
Reputation: 91
From what it looks like you are establishing the object of car, then you are calling the drive function from another file and passing the values audi and black through the variables model and color. Then you are returning the instance of the object ("start") with the variables and actions held inside it.
Upvotes: 1
Reputation: 29739
That's an encapsulation pattern.
car
holds an object with the structure seen in the return
statement.drive
function only exists in the scope of the surrounding function. You cannot call drive
from outside.car
is an object with one attributed named start
which is the function definition of drive
.If you call car.start
without parentheses you get the function definition itself:
function (model, color) {
...
}
This is because functions can be assigned to variables (first-class) without actually calling them, so that you can call predefined functions at a later time with a scope of your choice.
If you call car.start(audi, black)
you execute the function with the given parameters and get whatever is returned by the drive
function.
Upvotes: 2
Reputation: 943214
First it seems that in javascript a class
JavaScript doesn't have classes. The closest thing it has to them is constructor functions, but you don't have any of those here.
So how does this work
car
is the return value of an anonymous function that is called as soon as it is defined (it has ()
after the closing }
).
That return value is an object created using an object literal.
The value of the start
property of that object literal is the drive
function. Functions are first class objects in JavaScript so can be passed around just like any other kind of object.
Upvotes: 2