闭包编译器对此不应用@cconst
Closure Compiler does not apply @const on this
我正在尝试让这段代码正常工作:
/** @constructor */
function Foo()
{
/** @const */
this.bar = 5;
// edit: does now work
// this.bar = 3;
}
var f = new Foo();
// should be inlined (like other constants)
alert(f.bar);
我已经尝试添加更多的注释(类型、构造函数),@enum
而不是@const
(用于this.bar
)、me = this
,所有这些都没有任何效果。
帮助页面在这方面并没有真正的帮助。
有什么办法让它发挥作用吗?如果没有,为什么?
编译器没有任何通用的"内联属性"逻辑。您可以使用原型函数在ADVANCED模式下将其内联
/** @constructor */
function Foo() {}
Foo.prototype.bar = function() { return 5 };
var f = new Foo();
alert(f.bar());
将编译为:
alert(5);
如果方法"bar"只有一个定义,并且"bar"只在调用表达式中使用过,则编译器将执行此操作。在一般情况下,用于此操作的逻辑是不正确的(如果调用所在的对象没有定义调用将抛出的"bar")。然而,它被认为"足够安全"。
添加/** @constructor */
作品:
/** @constructor */
function Foo()
{
/** @const */
this.bar = 5;
// cc does not complain
//this.bar = 3;
}
var f = new Foo();
// should be inlined
alert(f.bar);
编译为:
alert((new function() { this.a = 5 }).a);
如果我取消注释this.bar = 3;
,我会得到预期的警告:
JSC_CONSTANT_PROPERTY_REASSIGNED_VALUE: constant property bar assigned a value more than once at line 9 character 0
this.bar = 3;
^
在文档中说:
如果一个用@cconst标记的变量被多次赋值,编译器将产生警告。If the variable is an object, note that the compiler does not prohibit changes to the properties of the object.
p.S.:您在脚本或HTML页面中包含了以下代码吗?
<script src="closure-library/closure/goog/base.js"></script>
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- Canvas Html5绘图应用程序,移动画布会导致重大问题
- Emberjs应用程序加载在除Index之外的所有路由上
- 使用电话间隙在Android应用程序中显示SQL Lite的数据
- 跟踪在页面加载时应用内联样式的JavaScript
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- 如果文本字段为空,则使用JavaScript应用CSS样式
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 为什么在单独的函数中应用时转换会闪烁/断断续续(D3)
- angular 1.5应用程序中的导航栏
- 在Web应用程序中使用Highcharts javascript
- angularjs+rails应用程序中未显示模板
- 从html创建一个指令,该指令按类名应用函数
- 使用acess代币登录Facebook,并通过网络应用程序离线发布
- 从HTTPGET返回一个自定义对象列表,以便在Angular 2应用程序中使用
- 科尔多瓦页面类应用程序中的多个谷歌地图
- 使用谷歌应用程序脚本将服务器端数据表返回到客户端
- Angularjs-utils高亮过滤器在搜索时破坏应用程序
- 在phonegap应用程序内部重定向不起作用
- 闭包编译器对此不应用@cconst