Just like in many other programming languages, objects in JavaScript can be compared to real life objects with various characteristics or properties. For example, a book has properties like color, shape, size, and so on. Hence, in JS, an object can be defined as a stand-alone entity with properties and types.
To create an object, we declare a variable and give it a name, after which we open the curly brace “{” where we write our properties. When you are done, you close the curly brace “}”and then you end with a semicolon. When listing the properties, it should be done in such a way that each property is on a separate line, and each line should end with a comma “,”. Let’s consider the example below.
var myBook = {
color: “blue”,
size : “A4”,
weight: 0.1,
};
We can display the contents of object on the console by simply typing the name of the object. In our case, we will be typing “myBook”. After typing, it produces the following output:
objectName.propertyName
Let us apply this in our example above to get the color property. We have
myBook.color
The code gives the following output :
var myBook = {
color: “blue”,
size : “A4”,
weight: 0.1,
show: function(message) {
alert(message);
},
};
To access a method, you begin by typing the name of the object, followed by a dot, the property name bearing the function and finally the brackets. That is
myBook.show(“Hello”)
The code produces the following output when typed on the console:
Comments
Post a Comment
Please do not enter any spam link in the comment box.