As a reminder methods are functions that belong to an object or class.
There are two types of object methods in javascript.
- Static
- Dynamic
Dynamic methods
The most common type of method is Dynamic. Dynamic methods are declared inside the object and are referenced from an instance of the object. For Example
function myobject(m){ //constructor for our object
this.message=m;
this.test=test; //assign test to this objects definition
}
function test(){ //global declaration of test function
alert(this.message);
}
// to use this function
o=new myobject('hello'); // creates a new myobject object.
o2=new object('goodbye'); //creates another object
//to reference this method
o.test(); //shows message 'hello'
o2.test(); //shows message 'goodbye'
There is another way of declaring the object without creating the function test using anonymous methods. ie
function myobject(m){ //constructor for our object this.message=m;
this.message=m;
this.test=function(){ //add parameters to function if required
alert(this.message);
}
}
Static or Class Methods
Most people find the difference between static and dynamic methods confusing. The main difference between the two is that a static method is referenced (or called) from the class and not an instance of the class.
function myobject(m){
}
function test(){
alert('class method');
}
//static methods are declared outside the class
//ie
myobject.test=test(); // here the method is assigned to the class itself
to call the method simply access classname.method ie
myobject.test();
Why use this when you can declare functions globally? ie
just
test();
rather than
myobject.test();
In some languages like c# all methods must be part of a class definition. This is of course not necessary in javascript. Here are a couple of reasons that you might think about
- Helps create structured and readable code
- For IDEs that have code completion methods can be exposed by typing the class name followed by period.

No comments:
Post a Comment