Created
May 6, 2016 14:16
-
-
Save ohvitorino/d06f24cd5df388e5f1bc2fcf3641f954 to your computer and use it in GitHub Desktop.
Classical javascript inheritance
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
// Classical prototypal inheritance | |
// This function comes from Node.js | |
function inherits(ctor, superCtor) { | |
ctor.super_ = superCtor; | |
ctor.prototype = Object.create(superCtor.prototype, { | |
constructor: { | |
value: ctor, | |
enumerable: false, | |
writable: true, | |
configurable: true | |
} | |
}); | |
}; | |
var Person = function (name) { | |
this.name = name; | |
} | |
Person.prototype.sayName = function () { | |
console.log("Hi my name is " + this.name); | |
}; | |
Person.prototype.shoutName = function () { | |
console.log("Hi my name is " + this.name + "!!"); | |
}; | |
var john = new Person("john"); | |
var bobby = new Person("bobby"); | |
var Musician = function (name, instrument) { | |
Musician.super_.call(this, name); | |
this.instrument = instrument; | |
} | |
inherits(Musician, Person); | |
Musician.prototype.getInstrument = function () { | |
console.log(this.instrument); | |
}; | |
Musician.prototype.shoutName = function () { | |
console.log("DUDE! My name is " + this.name + "!!!!"); | |
}; | |
var julia = new Musician("julia", "trombone"); | |
julia.sayName(); | |
julia.getInstrument(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment