Public / Private Methods - Inheritance (JS)
There are several ways to determine what and how to configure a public methods in JavaScript:
* = Public Method/Var, * = Private Method/Var
This is the way "Duglas Crockfor way" implements public methods, but I like more to see all the methods inside a unique container (as in Java or C++) and determine what is public or private with a simple distinguish symbol, in this case The "this" (for public).
This way the object (Company) remains the same instance of a Company type and not as the example before, while returning a new object, the instance of the object is not Company.
Also for me is more clear to show with "this" the Public Methods.
Remember that the Private Methods are also static, and private (Static) methods cannot call public (non-static) ones.
* = Public Method/Var, * = Private Method/Var
One way:
function Company(){
var name = null;
return {
setName: function(n){
name = n;
},
getName : function(){
return name;
}
}
}
This is the way "Duglas Crockfor way" implements public methods, but I like more to see all the methods inside a unique container (as in Java or C++) and determine what is public or private with a simple distinguish symbol, in this case The "this" (for public).
Second way (the one I prefer):
function Company(){
var name = null;
this.setName = function(n){
name = n;
}
this.getName = function(){
return getUppercase(name);
}
function getUppercase(str){
return str.toUpperCase();
}
}
This way the object (Company) remains the same instance of a Company type and not as the example before, while returning a new object, the instance of the object is not Company.
Also for me is more clear to show with "this" the Public Methods.
Remember that the Private Methods are also static, and private (Static) methods cannot call public (non-static) ones.

0 Comments:
Post a Comment
<< Home