Object can be also be created with the following two steps :
1. By writing a constructor function, define the object type. It would be better if we use a capital initial letter.
2. create an instance of obj with new.
To define an object type, create a function for the object type with its specified name, properties and its method. For example :
function Person(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
}
this keyword is to assign values to the object properties based on the value which we have passed to it to the function.
Now, create an object called humans :
var humans = new Person('ram',20,'male');
This creates humans and assign it to the properties with the specified values.
To retrieve these values : humans.name // "ram"
humans.age // 20
humans.gender // "male"
If we want to redefine the object Person. we can add the properties.
function Person(name, age, gender, city){
this.name = name;
this.age = age;
this.gender = gender;
this.city = city;
}
var details = new Person('sita',20,female,Hyderabad);
To retrieve these properties :
details.name // "sita"
1. By writing a constructor function, define the object type. It would be better if we use a capital initial letter.
2. create an instance of obj with new.
To define an object type, create a function for the object type with its specified name, properties and its method. For example :
function Person(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
}
this keyword is to assign values to the object properties based on the value which we have passed to it to the function.
Now, create an object called humans :
var humans = new Person('ram',20,'male');
This creates humans and assign it to the properties with the specified values.
To retrieve these values : humans.name // "ram"
humans.age // 20
humans.gender // "male"
If we want to redefine the object Person. we can add the properties.
function Person(name, age, gender, city){
this.name = name;
this.age = age;
this.gender = gender;
this.city = city;
}
var details = new Person('sita',20,female,Hyderabad);
To retrieve these properties :
details.name // "sita"
details.age // 20
details.gender // female
details.city // Hyderabad
we can always add a property for a previously defined object. For example
details.study = "B.E";
Adds this property to the details object and this doesn't effect the other object.
No comments:
Post a Comment