Last active
August 29, 2015 14:01
-
-
Save simplay/b0a91d4a833c9eeaafeb to your computer and use it in GitHub Desktop.
Example how to define a javascript class
This file contains hidden or 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
// a sample class decleration showing javascript closure examples. | |
// Keep in mind: prototyped properties affect all objects of the | |
// same constructor, simultaneously, even if they already exist. | |
function Knight(hp){ | |
// public attribute of Knight | |
this.hp = hp; | |
// private attribute of Knight | |
var secreteHP = hp+1; | |
// Privileged method: may access private members but is public accessible | |
// notice that it is not possible to extend a class (ignoring eval() magic) | |
// by a priviliged method | |
this.getSecreteHP = function() { | |
return "I have " + secreteHP.toString() + " secrete HP"; | |
} | |
} | |
// this is a public method which cannot access any private member of Knight instances. | |
// Note that using this kind of syntax allows a user to extend the class Knight | |
// with additional public members (i.e. methods or attributes) | |
// keep in mind that a public method only can access public members of its corresponding class | |
Knight.prototype.getHP = function(){ | |
return "I have " + this.hp.toString() + " secrete HP"; | |
}; | |
// this means, that a method invocation from a Knight instance, | |
// defined using prototypes, e.g.: | |
/* | |
Knight.prototype.getIdPr = function(){ | |
return "I have " + secreteHP.toString() + " secrete HP"; | |
}; | |
*/ | |
// does not work, since we cannot call secreteHP from a prototype's scope, | |
// since it is a private attribute. |
Author
simplay
commented
May 16, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment