This page is a work in progress.
(Early in its progress.)
Following are some advanced techniques for JavaScript classes.
JavaScript support static methods in various ways. (JavaScript supports stand-alone functions, so you don't need static methods for that purpose.)
What it boils down to is that, since functions are first-class objects in JavaScript, all you need to do is define a function and bind it to a one-of-a-kind object.
With our Point example, you could bind some functions directly to the Point() constructor function.
These functions would be available through the Point() function as an object.
For example, start with our friend the Point constructor, and add...:
functionPoint(x,y) {this.x = (x ==undefined? 0: x);this.y = (y ==undefined?this.x: y);this.Reset =function() {this.x = 0;this.y = 0; }this.Move =function(x,y) {this.x = x;this.y = y; }this.toString =function() {return'Point:x,y=' + this.x + ',' + this.y; } } // Create new Point function member... Point.GetNewPoint =function() {returnnewPoint(-1,-1); }
Use this new static method to return new objects with a specific value:
var o1 = new Point(21,42);
var o2 = Point.GetNewPoint();
Print(o1);
Print(o2);
When run, the output is:
Point:x,y=21,42 Point:x,y=-1,-1
| (back) | § | Top | Web | JavaScript | Tutorial |
|---|