Lasitha Yapa
Lasitha Yapa

Reputation: 4609

What does "variable : function(){}" means?

In a Node.JS example code I found a code block as follows.

var messageReceivedCallBack = {
    onMessageReceived: function (message) {
        console.log('Message received ' + message);
    }
};

What does this code means? Specifically I can't understand the part with the colon (' : ')

Upvotes: 0

Views: 67

Answers (3)

sjfkai
sjfkai

Reputation: 98

Maybe you can read: Object initializer and Method definitions

Upvotes: 1

slebetman
slebetman

Reputation: 113974

It's an object literal. That's not a variable, it's a property name:

var foo = {
   a: 1,
   b: 2
};

Is the same as:

var foo = {};
foo.a = 1;
foo.b = 2;

Similarly:

var foo = {
    a: function () {}
};

Is the same as:

var foo = {};
foo.a = function () {};

Therefore the following:

var messageReceivedCallBack = {
    onMessageReceived: function (message) {
        console.log('Message received ' + message);
    }
};

Is just doing this:

var messageReceivedCallBack = {};

messageReceivedCallBack.onMessageReceived = function (message) {
    console.log('Message received ' + message);
};

Upvotes: 5

Gopi
Gopi

Reputation: 163

In javascript, more ways to create objects/class.

  1. construction function based class (function ObjConstructor() {this.name="abc";})
  2. Object literals (var myObj = { "key" : "value" } (value can be function or number, string..,)

Here the : is separation of key value pair. If you look into the JSON, you can understand easily. JSON

Upvotes: 0

Related Questions