views:

17

answers:

1

I'm creating objects with private/public access restrictions as commonly promoted by Crockford. For example, I have something like this:

var foo = (function() {
    var myPrivateVariable = "whatever";
    return {
        myPublicFunction:function(str){
                    return str;
                }
    }
}());

If I issue a call, such as

myPublicFunction();

Closure should tell me that I'm invoking a function with the wrong number of arguments. I've tried helping Closure out with JavaDoc comments on myPublicFunction:

var foo = (function() {
    var myPrivateVariable = "whatever";
    return {
        /**
         * @param {string} str
         */
        myPublicFunction:function(str){
                    return str;
                }
    }
}());

foo.myPublicFunction();

Still, no complaint. I've tried various forms of JavaDocs for foo, and the only one that worked was to document it as a record type:

/**
 * @type {{myPublicFunction:funtion(string):string}}
 */
var foo = (function() {
    var myPrivateVariable = "whatever";
    return {
        /**
         * @param {string} str
         */
        myPublicFunction:function(str){
                    return str;
                }
    }
}());

foo.myPublicFunction();

That worked, but the compiler didn't try to enforce that the myPublic object function actually matched the signature I documented in the record field for the JavaDoc. So this will work so long as I make sure to doc all my functions in these returned objects and make sure I keep the signatures in my docs aligned with what I actually return. Am I missing some better way to enforce this?

Thanks!

+1  A: 

I would actually encourage you to take a look at using pseudo-classical inheritance, since the compiler smooths out the wrinkles. Michael Bolin has a detailed article describing this very issue.

http://bolinfest.com/javascript/inheritance.php

nullptr
Ah, very interesting. Thanks for your help (yet again--you helped me with my Closure question yesterday). My team and I are noodling on whether it's better to produce what we think of as true, more portable (if we decide not to continue with the Closure compiler) runtime information hiding rather than the Closure compile-time enforcement; or if we should go the way Closure prefers, since we'll get better results down the road. Right now, we're just tipping our toes into the Closure pool, using it just for error catching and not for compression, but down the line ...
Mr. Ubin
Oh, also, do you have any thoughts/comments on Closure's failure to enforce function signature declarations. I mentioned it at the end in my post, but if I write /** @type {function(string)} */ var foo = function(){};, the compiler doesn't notice the disparity.
Mr. Ubin

related questions