
Creating Methods in JavaScript
In object-oriented programming parlance, methods are simply functions that belong to a specific class or object. JavaScript makes this easy by allowing functions as first-class members. See the example below:
function PointObject(x, y)
{
/* Fields */
var x;
var y;
/* Methods */
var getX;
var getY;
getX = function()
{
return (this.x);
};
getY = function()
{
return (this.y);
};
this.x = x;
this.y = y;
return ({
getX:getX,
getY:getY
});
}
var Point;
Point = new PointObject(5, 10);
The most important to notice in the code above is that JavaScript has first class functions. This means that functions can be passed as arguments to other functions, be returned as values from other functions, and assign them to variables-just the same as any other data type. In the above example, we declare two functions (methods) called getX and getY. We then expose those references using the techniques we used in our last article.
The other thing to notice is that since these functions themselves are declared internally to our PointObject, they have reference to other variables that are declared inside of our PointObject, notably our 'x' and 'y' fields. In this way you can create setters and getters, popular techniques in object-oriented programming. We make our fiels priate to enforce encapsulation, and then access them through specific methods.
Next time we'll be looking at how to create static elements in JavaScript.
No comments:
New comments are not allowed.