Created
March 8, 2014 15:14
-
-
Save svenoaks/9432055 to your computer and use it in GitHub Desktop.
JavaScript invoking "super" functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// define the Person Class | |
function Person(name) { | |
this.name = name; | |
this.hasSaidHello = false; | |
} | |
Person.prototype.walk = function(){ | |
alert ('I am walking!'); | |
}; | |
Person.prototype.sayHello = function(){ | |
alert ('hello I am a Person'); | |
this.hasSaidHello = true; | |
}; | |
// define the Student class | |
function Student(name) { | |
// Call the parent constructor | |
Person.call(this, name); | |
}; | |
// inherit Person | |
Student.prototype = new Person("aStudent"); | |
// correct the constructor pointer because it points to Person | |
Student.prototype.constructor = Student; | |
// replace the sayHello method | |
Student.prototype.sayHello = function(){ | |
Person.prototype.sayHello.call(this); | |
alert("But I am also a Student"); | |
}; | |
// add sayGoodBye method | |
Student.prototype.sayGoodBye = function(){ | |
alert('goodBye'); | |
}; | |
var student1 = new Student("John"); | |
student1.sayHello(); | |
student1.walk(); | |
student1.sayGoodBye(); | |
// check inheritance | |
alert(student1 instanceof Person); // true | |
alert(student1 instanceof Student); // true | |
alert("Student1 has said Hello?: " + student1.hasSaidHello); | |
alert("Student1's name is " + student1.name); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment