Skip to content

Instantly share code, notes, and snippets.

@ConnerAiken
Last active April 26, 2018 20:13
Show Gist options
  • Save ConnerAiken/6037bc146bb307610542f299cb95d0c7 to your computer and use it in GitHub Desktop.
Save ConnerAiken/6037bc146bb307610542f299cb95d0c7 to your computer and use it in GitHub Desktop.
ES5 "Classes": Methods in Function() vs Prototype
// Version 1
// In this version, makeSound will be redeclared for every instance.
// Not horrible but can cause more memory utilization than needed.
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
this.makeSound = function() {return "The " + this.type + " named " + this.name + " goes " + this.sound + "!";};
}
// Version 2
// In this version, makeSound will be only be declared once
function AnimalSkinny(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
AnimalSkinny.prototype.makeSound = function() {
return "The " + this.type + " named " + this.name + " goes " + this.sound + "!";
};
var frogFat = new Animal('frog', 'Conner', 'ribbit');
var frogSkinny = new AnimalSkinny('frog', 'Conner', 'ribbit');
console.log("Emitting frogFat", frogFat);
console.log("frogFat spoke:"+frogFat.makeSound());
console.log("Note how the method is visible and declared to the class instance.");
console.log("\n\n");
console.log("Emitting frogSkinny", frogSkinny);
console.log("frogSkinny spoke:"+frogSkinny.makeSound());
console.log("Note how the method is not declared on the class instance but under the protoObject");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment