Suppose you have a variable that is common to all object instances, but you want to keep that private. In other languages you would create a static variable. Unfortunately, JavaScript does not support static or class variables.
You can obtain similar results in JavaScript by adding the common (i.e. shared) members to the prototype property of the constructor. In the example below, the label variable is shared among all the object instances created using the Book() constructor function. The label property is only accessible through the getLabel() prototype method.
Run
- function Book(author) {
- var author = author; // private instance variable
- this.getAuthor = function () {
- return author; // privileged instance method
- };
- }
- Book.prototype = (function () {
- var label = "Author: "; // private prototype variable
- return {
- getLabel: function () { // privileged prototype method
- return label;
- }
- };
- }());
- var book1 = new Book('James Joyce');
- alert(book1.getLabel() + book1.getAuthor()); // => Author: James Joyce
- var book2 = new Book('Virginia Woolf');
- alert(book2.getLabel() + book2.getAuthor()); // => Author: Virginia Woolf
Prototype functions are shared by all object instances. They are often used because it removes the need to create a function for each instance which saves memory and performs better. It is important to note that prototype functions have only access to prototype variables and not to private variables, such as the author variable in the example above.
No comments:
Post a Comment