0

I am completely new to javascript. I saw the below snippet in a tutorial. But i am not sure why do we use funtionName: function in return statement.

For example, getID:function() and setID: function() in the below code. Can anybody explain.

function celebrityID () {
    var celebrityID = 999;

    return {
        getID: function ()  {

          return celebrityID;
        },
        setID: function (theNewID)  {

            celebrityID = theNewID;
        }
    }

}
5
  • That's the object literal syntax. It's used to, well, create objects. Commented Jul 5, 2017 at 7:10
  • I am not sure what you are confused about. Since, JS has first class functions so functions can be stored in variable and as object properties. And here celebrityID function is returning an object with two properties which are functions and can be invoked later. Simple. Commented Jul 5, 2017 at 7:10
  • 1
    So that in future any celebrity could get and set the celebrityID like so. var celebrity = celebrityID() and celebrity.getID() or celebrity.setID(20000) Commented Jul 5, 2017 at 7:10
  • @bugwheels94 :Thank you. It is clear now. Commented Jul 5, 2017 at 7:13
  • @Alvaro Gonzalez: Thank you. It is clear now. Commented Jul 5, 2017 at 7:13

2 Answers 2

1

in your celebrityID () function you are returning an object, which has two properties those properties are function.

you can call

var myVar = new celebrityID();

myVar.getID(); // myVar = 999

this like object creation from a class

Sign up to request clarification or add additional context in comments.

Comments

0

So they can use it as

var cid = celebrityID();
var celbId = cid.getID();

If you do not have the return statement the function getID() will not be useful and also celbId becomes undefined.

If you closely observe, there is no return statement for setter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.