Skip to content

Instantly share code, notes, and snippets.

@jongrover
Last active September 27, 2016 16:51
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 jongrover/87293d96a7128c4f958c2f329d4370c7 to your computer and use it in GitHub Desktop.
Save jongrover/87293d96a7128c4f958c2f329d4370c7 to your computer and use it in GitHub Desktop.
Comparing Classical Inheritance vs Prototypal inheritance in Ruby vs JavaScript
function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function () {
return this.name + " says bark bark!"; // Storing things on the prototype will be accessible to all dogs but will only take up memory in a single place once time.
};
var dog1 = new Dog("Fido");
var dog2 = new Dog("Snoopy");
dog1.bark(); // Fido says bark bark!
dog2.bark(); // Snoopy says bark bark!
class Dog
def initialize(name)
@name = name
end
def bark
return "#{@name} says bark bark!"
end
end
dog1 = Dog.new("Fido")
dog2 = Dog.new("Snoopy") # Every time we create a new dog we are duplicating the logic for how it should bark (this takes up more memory for each dog).
dog1.bark # Fido says bark bark!
dog2.bark # Snoopy says bark bark!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment