开发者

Why won't the Closure Compiler enforce function signatures for objects returned from anonymous functions?

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;
           开发者_JAVA百科     }
    }
}());

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:function(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!


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


You have not provided any type information to "foo". You have provided type information to a property (myPublicFunction) of an object.

Your "record type" JsDoc actually puts type info on "foo" so it works.

This is the expected behavior from the compiler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜