【发布时间】:2012-10-28 13:54:22
【问题描述】:
我现在正在尝试使用高级选项使用闭包编译器缩小生产代码。代码使用Paul's client side cookie libraries。编译器会生成 30 多个这样的警告:
JSC_USED_GLOBAL_THIS: dangerous use of the global this object
以下是 Paul 库中的一些代码 sn-ps(原始代码使用命名函数,而不是匿名函数):
var cookieObject = function (name, expires, accessPath) {
var i, j
this.name = name
this.fieldSeparator = "#"
// this.found = false
this['found'] = false; // don't allow Closure-Compiler to rename
this.expires = expires
this.accessPath = accessPath
this.rawValue = ""
this.fields = new Array()
this.fieldnames = new Array()
if (arguments.length > 3) { // field name(s) specified
j = 0
for (i = 3; i < arguments.length; i++) {
this.fieldnames[j] = arguments[i]
j++
}
this.fields.length = this.fieldnames.length
}
this.read = ucRead // function assignments
this.write = ucWrite
this.remove = ucDelete
this.get = ucFieldGet
this.put = ucFieldPut
this.namepos = ucNamePos
this.read()
}; // cookieObject
uc 函数通常是这样构造的:
var ucRead = function () {
var search = this.name + "="
var CookieString = document.cookie
this.rawValue = null
this.found = false
}
我已阅读 How does “this” keyword work within a JavaScript object literal? 以及 Closure Compiler Warning dangerous use of the global "this" object? 和 Scope in JavaScript。但是,我仍然不明白上述代码中this 的范围是什么,也不明白如何重写这段代码以消除编译器警告。
Q1:谁能帮我澄清一下this的范围是什么?
Q2:有人可以提供一些代码 sn-ps 显示如何重写上述代码以消除编译器警告(我假设必须消除使用 this)?
TIA。
【问题讨论】:
-
this起初可能会让人感到困惑和棘手(当你认为你明白了之后,仍然会让你措手不及)。但是MDN provides a lot of info to get you started
标签: javascript scope google-closure-compiler