Skip to content

Instantly share code, notes, and snippets.

@benwells
Created March 26, 2014 13:10
Show Gist options
  • Save benwells/9782778 to your computer and use it in GitHub Desktop.
Save benwells/9782778 to your computer and use it in GitHub Desktop.
Define Object Methods inside class vs. added to prototype
/**
* Define a method inside of a JavaScript Object. In this instance, the method gets
* recreated with each Class Instance. Sometimes desirable, sometimes not.
*/
function Wizard () {
this.name = "The Wiz";
this.level = 1;
this.shoot = function () {
alert('Imma Shoot You!');
};
}
/**
* Alternatively, you can add a method to the object's Prototype. This is an
* more inexpensive way to add a method as the method gets added only once
* to the protype of the object's constructor function. The method will
* still be available to all class instances.
*/
function Wizard () {
this.name = "The Wiz";
this.level = 1;
}
Wizard.prototype.shoot = function () {
alert("Imma Shoot You!");
};
@GalCohen
Copy link

When would the first example be desirable over the prototype approach?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment