Last active
August 29, 2015 14:01
-
-
Save wehrhaus/e71f2fc4a502a61ee5e0 to your computer and use it in GitHub Desktop.
Superconstructor / Subconstructor Example
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
// Superconstructor | |
function Person(name) { | |
this.name = name; | |
} | |
Person.prototype.sayHelloTo = function (otherName) { | |
console.log(this.name + ' says hello to ' + otherName); | |
}; | |
Person.prototype.describe = function () { | |
return 'Person name ' + this.name; | |
}; | |
// Subconstructor | |
function Employee(name, title) { | |
Person.call(this, name); | |
this.title = title; | |
} | |
Employee.prototype = Object.create(Person.prototype); | |
Employee.prototype.describe = function () { | |
return Person.prototype.describe.call(this) + ' (' + this.title + ').'; | |
}; | |
var jack = new Person('Jack'), | |
jill = new Employee('Jill', 'Water Fetcher'); | |
jack.name; //=> 'Jack' | |
jill.name; //=> 'Jill' | |
jack.sayHelloTo(jill.name); //=>'Jack says hello to Jill' | |
jill.sayHelloTo(jack.name); //=> 'Jill says hello to Jack' | |
jack.describe(); //=> 'Person name Jack' | |
jill.describe(); //=> 'Person name Jill (Water Fetcher).' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment