0

I am trying to properly annotate all my Javascript code and am still a beginner in this field.

I get objects from a server call that are directly in json. Those objects are passed to functions and I call members directly. It obviously is very error prone while obfuscating so I am trying to annotate everything properly.

My understanding is that (i) I should create a class for this object even though it is never created directly with new and (ii) I should be careful with member names since they are fixed by the server response and should not be changed (or should be aliased beforehand).

I have two questions: are my asumptions correct ? how to do the annotation based on that.

Here is a sample code to illustrate

$.get("url.php", function(data) {
    process(data);}, "json"); // <= returns {"a":"abc","b":1}

function process(data) {
  $("#someElement").html(data.a + data.b);
}

Here is the class I was planning on creating for closure compilation purposes

/**
 * The object that is sent back from the server
 * @constructor
 */
function ServerResponse() {
  /** @type {string} a */
  this["a"] = "";
  /** @type {number} b */
  this["b"] = 0;
}

Here is the annotation for my process function

/**
 * Process data from the server
 * @param {ServerResponse} data: the Object sent back from the server
 */

Is my annotation correct? Is it robust to obfuscation?

Thanks a lot for your help

4

1 回答 1

1

如果您引用属性名称,则需要在每次使用时一致地引用它们。如果你还没有看到这个,你应该阅读:

https://developers.google.com/closure/compiler/docs/api-tutorial3

这样您的第一个片段将是:

function process(data) {
  $("#someElement").html(data['a'] + data['b']);
}

如果您试图避免引用,或者您希望编译器键入检查属性的使用情况(不检查引用的属性引用),您应该定义一个 extern 文件以包含在您的源代码的编译中:

/** 
 * @fileoverview
 * @externs
 */

/** @interface */
function ServerResponse() {}
/** @type {string} */
ServerResponse.prototype.a;
/** @type {number} */
ServerResponse.prototype.b;
于 2012-04-23T16:41:30.897 回答