【问题标题】:reformat javascript to accommodate google-closure-compiler's namespace flattening格式化 javascript 以适应 google-closure-compiler 命名空间展平
【发布时间】:2013-07-26 20:18:29
【问题描述】:

google-closure-compiler 在高级模式下,警告以下代码。这是由命名空间扁平化引起的。

var com.my.test.namespace = {};
com.my.test.namespace.a = new Class ({
    name : "test",
    initialize : function() {   //constructor
        alert(this.name);
    }
});

com.my.test.namespace.a();

在启用调试的高级模式下运行 google-closure-compiler 时,com.my.test.namespace.a 被替换为 com$my$test$namespace$a

所以,缩小后的代码大致如下,

var com.my.test.namespace = {};
com$my$test$namespace$a = new Class ({
    name : "test",
    initialize : function() {   //constructor
        alert(this.name);
    }
});

com$my$test$namespace$a();

当调用 com$my$test$namespace$a() 时,“this”不再是 com.my.test.namespace,它是窗口,因此是编译器警告。

一些文档建议将“this”替换为 com.my.test.namespace.a 以解决此问题。但是,这样做是正确的吗? com.my.test.namespace.a.name 指向什么?它肯定不像当前实例的“名称”属性。

正确的做法是什么? com.my.test.namespace.a.prototype.name ?

PS:
I am using mootools library for the Class method.

【问题讨论】:

  • 你用 new 实例化一个类构造函数。即new com$my$test$namespace$a();,此时this 将成为您的新对象实例。

标签: javascript performance mootools google-closure-compiler yui-compressor


【解决方案1】:

如果 initialize 是构造函数,那么“this”应该是类型的名称而不是命名空间。这是编译器应该如何注释的方式

/** @const */
var namespace = {};

/** @constructor */
namespace.a = new Class (/** @lends {namespace.a.prototype} */{
    name : "test",
    initialize : function() {
        alert(this.name);
    }
});

new namespace.a();

这是我所拥有的:

  1. 一个 const 命名空间。不是必需的,但改进了类型检查。
  2. 构造函数声明(引入类型名称)
  3. 对象字面量上的@lends,表示属性正在用于类型声明。

@lends 在这里是必要的,因为闭包编译器没有内置关于 Moo 工具类声明的任何特定知识,您需要帮助它了解它被用作类型定义的一部分。

【讨论】:

  • 使用“this”的警告是否危险,因为闭包编译器不理解这个方法是构造函数?
  • 因为它根本不知道自己是一个类的成员。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 2011-05-12
相关资源
最近更新 更多