What is an object
object is a special kind of data which properties and methods.
We can create objects in multiple ways.
1.
var obj1={
name:"John",
age:20
};
2.
var obj2=new Object();
obj2.name="Jim";
obj2.age=30;
How create a object within a object for example create a object(obj3) within (obj1)
var obj1={
name:"John",
age:20,
obj3={
city:"Enschede",
country:"The Netherlands"
}
};
How to access the properties and the values
console.log(obj1.name);//output is John
console.log(obj1.age);//20
console.log(obj2.name);//Jim
console.log(obj2.name);//30
console.log(obj1.obj3.city);//Enschede
console.log(obj1.obj3.country);//The Netherlands
How to create functions.
Syntax is as below.
var functionname=function(){
};
Example
var display=function(name,age){
this.name=name;
this.age=age;
};
or
function display(name,age){
this.name=name;
this.age=age;
};
lets create an example in which different object try to access a single method.
1. create an object.
var object1={
name:"John",
age:30
};
2. Create the method.
var method1=function(name,age){
this.name=name;
this.age=age;
};
3. Relate the object to the method.
object1.method1=method1;
4. check the output.
console.log(object1.name);//John
console.log(object1.age);//30
object1.method1("Jason",40);
console.log(object1.name);//Jason
console.log(object1.age);//40
or you can also use this
function function1(name,age){
this.name=name;
this.age=age;
};
var obj1=new function1("John",30);
var obj2=new function1("Jason",32);
console.log(obj1.name);
console.log(obj1.age);
console.log(obj2.name);
console.log(obj2.age);
Concludes by using this keyword we can use as many objects as possible.
How to add a new property to an object.
consider the below object
var obj4={
name:"Helen",
age:35
};
obj4.city="london";
console.log(obj4.city);//london
Hope this post was informative, will get back with more updates.
No comments:
Post a Comment