Constant generic accessor method:
If you have a lot of constants and don’t want to create an accessor method for each, you
can create a single generic accessor method:
var Class = (function() {
//Private static attributes.
var constants = {
UPPER_BOUND: 100,
LOWER_BOUND: -100
};
//Privileged static method. (keep in mind, IT'S NOT PRIVATE!!!)
this.getConstant = function (name) {
return constants[name];
}
//Return the constructor.
return function(constructorArgument) {
//Private attributes.
var isbn, title, author;
//Privileged methods.
this.getTitle = function() {
return title;
};
this.setTitle = function(newTitle) {
title = newTitle || 'No Title specified';
};
}
})();
Usage: try it in Firebug
Then you would get a constant by calling the single accessor:
Author's suggestion in the book is not working, since it get's propagate the prototype chain all the way to the Object in javascript hierarchy.
Class.getConstant('UPPER_BOUND'); //(Book's example) not working it went up prototype chain to the Object
getConstant('UPPER_BOUND'); //working = returns: 100
//in firebug if you do somethig like this:
var cl = new Class ('mynewtitle');
cl.getConstant('UPPER_BOUND'); //error not function
getConstant instanceof Object; //returns true
getConstant instanceof Function; //returns true
getConstant instanceof Class; //returns false
getConstant instanceof window; //returns false
Here, we call getConstant method as is. I don't think this is what author meant as 'Privileged static method'.
No comments:
Post a Comment