2

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

4

2 回答 2

1

我实际上鼓励你看看使用伪经典继承,因为编译器消除了皱纹。Michael Bolin 有一篇详细的文章描述了这个问题。

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

于 2010-10-28T19:03:10.417 回答
0

您没有向“foo”提供任何类型信息。您已向对象的属性 (myPublicFunction) 提供类型信息。

您的“记录类型”JsDoc 实际上将类型信息放在“foo”上,因此它可以工作。

这是编译器的预期行为。

于 2011-03-09T05:12:56.693 回答