Skip to content

Instantly share code, notes, and snippets.

@kellishouts
Created January 30, 2015 02:45
Show Gist options
  • Save kellishouts/89802cf422e3f2f5604d to your computer and use it in GitHub Desktop.
Save kellishouts/89802cf422e3f2f5604d to your computer and use it in GitHub Desktop.
Javascript OOP Example
// 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