The Javascript syntax is very loose, so it it possible to define a Javascript class using a variety of techniques. I prefer the following method because it is easiest to comprehend and most closely resembles the traditional syntax used in other programming languages. First, define a normal function to serve as the class definition (Javascript does not actually have a "class" keyword, instead it uses functions to simulate classes). Second, define properties and methods inside the function by using the "this" keyword. Last, instantiate an object from the function by using the "new" keyword. Pass in any arguments the same as you would with a normal constructor. Below is an example:
function Apple(type) { this.type = type; this.color = 'red'; this.getInfo = function() { return this.color + ' ' + this.type + ' apple'; }; } var apple = new Apple('macintosh'); apple.color = 'reddish'; alert(apple.getInfo());
Note: Some people prefer to use the "prototype" keyword to define Javascript classes because it is more memory efficient. You can read more about this alternative method by following the link at the bottom of this post.
I copied and paraphrased most of the information in this post from the following link:
No comments:
Post a Comment