JavaScript is all about objects. In order to learn about object-oriented programming, we need to have a good understanding about objects.
JavaScript Object Literals:
In ECMA 6, to create a variable we use the keyword let. Before ECMA 6 was released, to create a variable we used to use var keyword. But, from ECMA 6 onwards, we use the keywords let or const. With const we cannot reassign the variable - because, it indicates a constant.
So, here I am creating a rectangle variable and assigning it to an object.
Here, the curly braces indicate an object literal syntax. In JavaScript, object is a collection of key value pairs.
In this object, the variables:
... are called properties.
The variable:
is another object. The location object consists of couple of key - value pairs :
Also we have the variable:
.. a function is assigned to this variable.
This rectangle object has 4 members:
If a member is a function, we call it - method. The other members are called properties.
We can call the members of an object using the dot notation (.). Since, we want to call the draw method from the rectangle object, we call it as:
JavaScript Object Literals:
In ECMA 6, to create a variable we use the keyword let. Before ECMA 6 was released, to create a variable we used to use var keyword. But, from ECMA 6 onwards, we use the keywords let or const. With const we cannot reassign the variable - because, it indicates a constant.
So, here I am creating a rectangle variable and assigning it to an object.
const rectangle = {};
Here, the curly braces indicate an object literal syntax. In JavaScript, object is a collection of key value pairs.
const rectangle = {
length:1,
width:5,
location: {
x:1,
y:1
},
draw: function(){
console.log("draw");
}
};
rectangle.draw();
In this object, the variables:
- length
- width
... are called properties.
The variable:
- location.
is another object. The location object consists of couple of key - value pairs :
- x
- y
Also we have the variable:
- draw
.. a function is assigned to this variable.
This rectangle object has 4 members:
- length
- width
- location
- draw
If a member is a function, we call it - method. The other members are called properties.
## |
Member Name |
Member Type |
1 |
length |
property |
2 |
width |
property |
3 |
location |
property |
4 |
draw |
method |
We can call the members of an object using the dot notation (.). Since, we want to call the draw method from the rectangle object, we call it as:
rectangle.draw();
No comments:
Post a Comment