Skip to content

Instantly share code, notes, and snippets.

@jameswomack
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jameswomack/9463458 to your computer and use it in GitHub Desktop.
Save jameswomack/9463458 to your computer and use it in GitHub Desktop.
Shallow Inheritance in JavaScript
var A = function (neighborhood) {
this.neighborhood = neighborhood;
}
A.prototype.getInitial = function () {
return this.neighborhood[0];
}
A.prototype.getLast = function () {
return this.neighborhood[this.neighborhood.length-1];
}
var B = function (neighborhood) {
A.call(this, neighborhood.concat('!'));
}
B.prototype = A.prototype;
B.prototype.getExclamatoryInitial = function () {
return this.getInitial().concat(this.getLast());
}
var a = new A('Shinagawa');
var b = new B('Shinagawa');
try {
console.log(a.getExclamatoryInitial());
} catch(e) {
e && console.log(e);
}
console.log(b.getExclamatoryInitial());
delete A.prototype.getExclamatoryInitial;
B.prototype = Object.create(A.prototype);
B.prototype.getExclamatoryInitial = function () {
return this.getInitial().concat(this.getLast());
}
var a = new A('Shinagawa');
var b = new B('Shinagawa');
try {
console.log(a.getExclamatoryInitial());
} catch(e) {
e && console.log(e);
}
console.log(b.getExclamatoryInitial());
/*
Sa
S!
[TypeError: Object [object Object] has no method 'getExclamatoryInitial']
S!
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment