Created
March 26, 2014 13:10
-
-
Save benwells/9782778 to your computer and use it in GitHub Desktop.
Define Object Methods inside class vs. added to prototype
This file contains 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
/** | |
* 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!"); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When would the first example be desirable over the prototype approach?