So I've been looking into full development object oriented JavaScript practices, and wonder about the following examples.
As I understand it, (and it makes sense to me) that the following 'secret' field is 'private' :
var MyObject = function() {
var secret = 'sshhh';
this.getSecret() = function() {
return secret;
}
}
and this is because the field secret has function scope that the inner function can access, but nothing outside ... so far so good.
But I've seen the following around (and especially in Douglas Crockford's book) :
var MyObject = function() {
var secret = 'sshhh';
return {
getSecret : function() {
return secret;
}
}
}();
and was wondering what the difference is, why is it better? I understand that in this case we're not even returning the same object that the private field exists in, but don't see a huge benefit as you can't access the field directly either way.
>), but by indenting it with 4 spaces (use thecodebutton in the editor pane, instead of thequotebutton).