Created
January 30, 2015 02:45
-
-
Save kellishouts/89802cf422e3f2f5604d to your computer and use it in GitHub Desktop.
Javascript OOP Example
This file contains hidden or 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
// oop.js | |
// Class Definition (is Capitalized) | |
function Animal ( name ) { | |
// class constructor | |
// instance properties | |
this.name = name; | |
this.last_ate = null; | |
console.log('created a new Animal named', this.name); | |
} | |
// Instance method | |
Animal.prototype.eat = function( food ) { | |
this.last_ate = food; | |
console.log(this.name, "noms on", this.last_ate); | |
} | |
// Instance method | |
Animal.prototype.poop = function() { | |
console.log(this.name, "poops!!!"); | |
}; | |
// Subclass Definition / Constructor method | |
function Dog () { | |
// instance properties | |
this.breed = null; | |
// call super constuctor | |
Animal.call(this, "unnamed dog"); | |
} | |
// extend Animal class | |
Dog.prototype = Object.create(Animal.prototype, { | |
constructor : { | |
value : Animal | |
} | |
}); | |
function Cat ( name, color ) { | |
// Instance properties | |
this.color = color; | |
// call super constructor | |
Animal.call(this, name); | |
} | |
// extend Animal class | |
Cat.prototype = Object.create(Animal.prototype, { | |
constructor : { | |
value : Animal | |
} | |
}); | |
var maru = new Cat("Maru", "black and white"); | |
maru.eat( "cat fud" ); | |
maru.poop(); | |
console.log( maru ); | |
// create a new instance of dog | |
var jake = new Dog(); | |
jake.name = "Jake"; | |
jake.eat("Everything Burrito"); | |
console.log(jake); | |
// create a new instance of Animal | |
var rizzo = new Animal( "Rizzo" ); | |
rizzo.eat( "pizza" ); | |
rizzo.poop(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment