Monday, August 4, 2014

"classes" in JavaScript (and encapsulation, inheritance, and methods too)

By brain tries to juggle the difference in common computer science concepts between C# and JavaScript. Yes, there is not private versus public in JavaScript, but one may still have encapsulation nonetheless by just nesting one function inside of another allowing only the outer function to use the inner function. This touches on three ways to make "classes!" (There is NOT really such a thing as a class in JavaScript.) The first is to just make an instance of a named function like so:

function Orange (valueToMsPacman) {
   this.name = "Orange";
   this.points = valueToMsPacman;
}
Orange.prototype.description = function() {
   return "The " + this.name + " is worth " + this.points + "!";
}
var orange = new Orange(500);
alert(orange.name);
alert(orange.points);
alert(orange.description());

 
 

The link I just gave also recommends bolting on function functionality that is never going to vary from instance to instance with the prototype inheritance trick in lieu of recreating it every time an instance of a named function is made (by nesting it in the function). This entails less overhead. I always wondered why I should care about JavaScript's lightweight inheritance and now I know why. You may see the inheritance stuff in action in the code above. Also, I offer a reminder. (I think I have blogged of this before.) A method in JavaScript is a function hanging off of a JSON object as a property like so:

var orange = {
   name: "Orange",
   points: 500,
   description: function() {
      return "The " + this.name + " is worth " + this.points + "!";
   }
};
alert(orange.name);
alert(orange.points);
alert(orange.description());

 
 

The author (Stoyan Stefanov) of the blog post at the link I provide at the very top of this blog posting would also consider the JSON object I just showed off to be a "class." There is also one last way to make a "class" per Mr. Stefanov and that is like so:

var orange = new function() {
   this.name = "Orange";
   this.points = 500;
   this.description = function() {
      return "The " + this.name + " is worth " + this.points + "!";
   };
};
alert(orange.name);
alert(orange.points);
alert(orange.description());

 
 

This is more or less the same thing as the prior example, however commas become semicolons, colons become equals signs, and "this" gets thrown into the mix.

No comments:

Post a Comment