methods in a object can be thought as functions associated with an object.
ex:
obj.method = function(){
};
methods can be used to change property values.
if we want to use the method for other objects as well, for this we use ‘this’ keyword.
first we define a method
var setAge = function(newage){
this.age = new(newage);
}
now we define our object
var obj = new Object();
obj.age = 22;
obj.setttingnewage = setAge; //this acts as a placeholder, it will store whichever object called this
obj.settingnewage(23); // method, so now whenever we type obj.settingnewage(23), this.age
// in the method will refer to bob.age . here this holds obj, since obj called it.
***we can define objects inside objects in javascript.
I tried to create objects by 2nd method using ‘new’ keyword. here ‘Object’ is the constructor. it is already defined by javascript. Now i am learning that we can make custom constructors as well.
the Object function constructor creates a object with no properties and we have to manually add them.
so we create custom constructors instead.
ex:
function Person(name, age){
this.name = name;
this.age = age;
}
so now we have ‘Person’ constructor, we can create person objects much easily here
var bob = new Person(“bob”, 22); // properties are already defined
we can also initialize properties inside a constructor not just define them.
ex:
function Person(name, age){
this.name = name;
this.species = “Homo Sapien”;
} // we initialized the property species here.
**** Not just properties, we can also define methods directly inside constructors.
**** I know object is just like string or integer just like any variables. like we have done a array of integer and strings, we can also make a array of objects
ex : var family = new Array();
family[0] = new Person(“sur”,22);
family[1] = new Person(“bur”,23);
arrays filled with objects will work just like arrays filled with strings or integers.
*** we can send objects as argument to a function, just like we send int or string as arguments
Math.PI -this func gives the value of pi