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:
[js]
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;
}
}
[/js]

To compile js2 file into js file in lib directory run the command given below:
[bash]
js2-node compile -f=node ./src ./lib
[/bash]

Now create a js script named as inheritance.js in scr directory with following content:
[js]
var Person = require(‘../lib/InheritanceTest’).Person;
var Employee = require(‘../lib/InheritanceTest’).Employee;

var person = new Person(“Amit”, “Thakkar”);
console.log(person.toString())
var employee = new Employee(“Amit”, “Kumar”, “Intelligrape”);
console.log(employee.toString())
[/js]

Now run inheritance.js file with the command given below:
[bash]
node src/hello.js
// Output
Amit Thakkar
Amit Kumar, Intelligrape
[/bash]

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *