Object-Oriented JavaScript Basic Tips for Beginners


Object-Oriented JavaScript Basic Tips for Beginners

Object-Oriented JavaScript Basic Tips for Beginners

Custom-made JavaScript objects can have example methods (function that are connected with a certain JavaScript object), but like various other Object-Oriented languages, they could also have static methods, that is functions that are related to the JavaScript class that produced an object, instead of the object itself. This works in cases where a function (a.k.a. a method) will certainly not be different in different object instances. Let’s take a look at an example …

Object-Oriented JavaScript Basic Tips for Beginners

If you created a class to handle basic math calculations:

function Calculator()

{

}

To start with, an instance method could be included in this class in one of two ways, either inside the fabricator or through the class prototype. In this instance, one method called multiply will be created, which returns the item of two values multiplied together. Initially, applied in the constructor it looks like:-

function Calculator()

{

this.multiply = function(val1 , val2)

{

return (val1*val2);

}

}

Via the class model (prototype), which is a more readable solution in my point of view, it would certainly look like:-

function Calculator()

{

}

 

Calculator.prototype.multiply = function(val1 , val2)

{

        return (val1*val2);

}

Use this method would certainly then occur with instance of the Calculator class, thus:-

var calc = new Calculator();

alert( calc.multiply(4,3) ); //pop-up alert with product of 4 times 3

Nevertheless, it should not really be necessary to create an object use the multiply method, because the method isn’t based on the state of the object for its implementation. The method can be transferred to the class to clean up this code a bit. First the class meaning is created, which looks nearly the same to the instance method declaration above, with the exception of the model search phrase being removed:-

function Calculator()

{

}

 

Calculator.multiply = function(val1 , val2)

{

return (val1*val2);

}

Currently the multiply method could be called via the class itself, instead of an instance of the class, thus:-

alert( Calculator.multiply(4,3) ); //pop-up alert with product of 4 times 3

I am a graphic and web designer in Delhi and Professional Web and Graphics Designer & Animator. I provide SEO Service in Delhi along with SEO, Web and Graphics Designing Courses training with latest technique.