
Creating Methods in JavaScript
We've looked at creating methods and fields directly on an object literal and also on instances of a class(technically instances of the function object), but what if we wanted to assign these elements to the class itself? What if we wanted there to be only a single instance of this method or field? This would be the equivalent of using the static keyword in languages such as Java, and in JavaScript it's extremely easy to setup. See below.
var PointObject = function(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
});
}
PointObject.msg = function()
{
alert("Your browser supports the PointObject");
};
var Point;
Point = new PointObject(5, 10);
We've taken the PointObject class we've been developing over the last few examples and added a function('msg') directly to the class definition. That's all there is to it. You can now invoke that 'msg' method by calling PointObject.msg(). The same technique works on fields as well.
Next time we'll look at using constructors in your JavaScript objects.
No comments:
New comments are not allowed.