Skip to content

Instantly share code, notes, and snippets.

@simplay
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simplay/b0a91d4a833c9eeaafeb to your computer and use it in GitHub Desktop.
Save simplay/b0a91d4a833c9eeaafeb to your computer and use it in GitHub Desktop.
Example how to define a javascript class
// 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.
@simplay
Copy link
Author

simplay commented May 16, 2014

knight = new Knight(100);

knight.getHP();
>> "I have 100 secrete HP"

knight.getSecreteHP();
>> "I have 101 secrete HP"

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