Javascript: Objects

 A JavaScript Object may be a real life object or thing and its different kinds of looks, actions, varieties are the different properties of the object. The different ways of doing the actions are the methods of the object.

For example, a laptop is an object, its different model, size, color, memory are the properties and its processing speed, the way of functioning or different operating systems are the different methods.

The properties and method's name of different laptops are same but values of these properties and methods may be different.

An object may be a variable too, which can contain many values:

For example:

Try it yourself editor
 
Code
Output
An object may contain many values as a variable. The values are written by name:value pairs
For example: 
Try it yourself editor
 
Code
Output
A JavaScript object can be created as literals. 
For example: Try it yourself editor
 
Code
Output
In above examples, we can see that the laptop is an object, its type, model and color are properties. HP, pavilion and white are values of the properties.
We can access an object property by two ways. These are:
object.property or
object["property"]
See examples
Try it yourself editor
 
Code
Output
This is the first way as object.property 

Try it yourself editor
 
Code
Output
This is the second way as object["property"]
An object property can be defined as the container of the values.

Object Methods : Methods are the actions performed by an object or on an object. Methods are stored in a property as function definition.
For example:
var person = {
  firstName: "Peter",
  lastName : "Johnson",
  gender: "male",
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
A methos is a function stored as a property.
In above example 'this' refers to the object.
this.firstName = firstName property of this=firstName property of object or person.

Here, 'this' keyword refers to the object depending on how it is used or how 'this' is being invoked.

Remember 'this' is a keyword not a variable, so we can't replace it with other words.
Now see the syntax, how 'this' keyword works.

Try it yourself editor
 
Code
Output
Do not declaire strings, numbers and booleans as objects.
 When any javaScript variable is assigned with 'new' keyword, it is created as an onject.
For example:
x = new strings();  It declaire x as an string object. 
x = new numbers();  It declaire x as an number object. 
x = new booleans();  It declaire x as an boolean object. 

No comments:

Post a Comment

Python: Functions