I come from a Java/C++ OOP background and am trying to get into JavaScript “object-oriented” programming. I was looking through the source for a small framework and noticed something that I found odd. The framework defines some global functions, and then calls those functions from within the object’s functions. To clarify, here’s an example:
var MyObject = function() {
function MyObject() {
this.x = 5;
}
MyObject.prototype.getX = function() {
return _MyObjectGetX( this );
};
return MyObject;
}();
var _MyObjectGetX = function( myObject ) {
return myObject.x;
};
What I don’t understand is the usage of the global function. Let’s assume that global function is only used in one place: MyObject.getX(). Why not just move the return into the function body? Is this okay:
var MyObject = function() {
function MyObject() {
this.x = 5;
}
MyObject.prototype.getX = function() {
return this.x;
};
return MyObject;
}();
This framework was written in CoffeeScript and then translated into JavaScript. Is this something that CoffeeScript does that may be unnecessary, or am I completely misunderstanding how JavaScript handles functions and objects (or rather, functions as objects)?
EDIT: sorry, misread your question.
In this case it looks like coffeescript is just being dumb…sort of like wysiwyg generated html.
really has no advantage over the simpler
And the outer getter function used in the top coffeescript example seems to have no gain over a simple return. In fact, neither really seems to have a legitimate use for the getter, as there’s no encapsulation being provided. The x property is readily available (and modifiable) on the object no matter where it is passed.
There my be some reasons why the framework opted to do this…but for this simple example I don’t understand.