How to implement Inheritance in js2

18 / Feb / 2013 by Amit Kumar 0 comments

We are assuming that you have installed js2 in your system, in case if you have not installed js2, first install js2.

First of all create a InheritanceTest.js2 file in scr directory with the content given below:

class Person { // Parent class
    var firstName;
    var lastName;

    function initialize(firstName, lastName) { // Constructor
        this.firstName = firstName;
        this.lastName = lastName;

    function toString() {
        return this.firstName + ' ' + this.lastName;

class Employee extends Person { // Child class
    var companyName;

    function initialize(firstName, lastName, companyName) { // Constructor
        this.$super(firstName, lastName);
        this.companyName = companyName;

    function toString() {
        return this.$super() + ', ' + this.companyName;

To compile js2 file into js file in lib directory run the command given below:

js2-node compile -f=node ./src ./lib

Now create a js script named as inheritance.js in scr directory with following content:

var Person = require('../lib/InheritanceTest').Person;
var Employee = require('../lib/InheritanceTest').Employee;

var person = new Person("Amit", "Thakkar");
var employee = new Employee("Amit", "Kumar", "Intelligrape");

Now run inheritance.js file with the command given below:

node src/hello.js
// Output
Amit Thakkar
Amit Kumar, Intelligrape

Amit Kumar
More Blogs by Me


Leave a comment -