Skip to content

Instantly share code, notes, and snippets.

@wehrhaus
Last active August 29, 2015 14:01
Show Gist options
  • Save wehrhaus/e71f2fc4a502a61ee5e0 to your computer and use it in GitHub Desktop.
Save wehrhaus/e71f2fc4a502a61ee5e0 to your computer and use it in GitHub Desktop.
Superconstructor / Subconstructor Example
// 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