Inheritance and encapsulation is an essential tennant of OOP. JS does things a little bit differently than most languages, we’ll go over those differences in this post. It’s assumed you already have a basic familiarty w/ OO JS, if not head over my OO JS in 15mins or Less tutorial to cover the basics.
JavaScript technically doesn’t have classes but it does have constructors. Constructors act as containers for class variables and methods just like the class statement in other languages. Let’s start by creating a constructor function.
function Person() {};
Looks good, to bad it’s empty. Let’s tack on an instance variable and a method that can access that instance variable w/ prototype (Need a crash course on prototype in JS? See the posts by Yehuda Katz or Angus Croll).
Person.prototype.type = "Human";
Person.prototype.sayType = function() {
console.log("Type: " this.type);
}
var me = new Person();
me.sayType(); // "Type: Human"
Properties, methods, and the elusive this oh my what’s a developer to do? Read this guide to writing elegant object oriented (OO) JavaScript I respond!
Learning to write elegant JavaScript is important to your career as a developer. With the advent of technologies such as Node.js you can now write JavaScript on the server side, likewise you can even use JavaScript to query a persistent data store like MongoDB.
So let’s get started writing some OO JS. If you have any questions or I missed something please leave me a message in the comments.