In javascript, we can initialise a variable with {}. What does the "{}" mean?
var o = {};
o.getMessage = function ()
{
return 'This is an example';
};
return o;
In javascript, we can initialise a variable with {}. What does the "{}" mean?
var o = {};
o.getMessage = function ()
{
return 'This is an example';
};
return o;
This means you create an object with a variable Its known as object with literal notation.which seems like below .
var o = {}
here your object has no property or it can be say as empty literal block .But in the below code
var o = {
o .first= 20;
o .second= 10;
o.result =function(){
return this . first- this .second;
}
} ;
now you have your object with property and function
** though there are several ways of creating object But Literal notation is the easiest and popular way to create objects
Basically the different cases are:
Use {} instead of new Object()
Use "" instead of new String()
Use 0 instead of new Number()
Use false instead of new Boolean()
Use [] instead of new Array()
Use /()/ instead of new RegExp()
Use function (){} instead of new Function()
Basically, it is an empty object. When you add the getMessage()
function at the bottom of the variable, you actually added it to the empty object, resulting to your empty object now to look like this:
var o = {
getMessage: function() {
return 'This is an example';
}
};
You can create a scope or class with it, in which you can use closures to keep certain variables private within that scope.