JS Inheritance in 15mins or Less | blogatom.

beardedocto:

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.

Classes

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"

Read More