我有生产代码,现在我正在尝试使用高级选项使用 Closure Compiler 来缩小这些代码。该代码使用Paul 的客户端 cookie 库。编译器会生成 30 多个这样的警告:
JSC_USED_GLOBAL_THIS: dangerous use of the global this object
以下是 Paul 库中的一些代码片段(原始代码使用命名函数,而不是匿名函数):
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
}
我已经阅读了“this”关键字在 JavaScript 对象文字中是如何工作的?以及关闭编译器警告危险使用全局“this”对象?和JavaScript 中的范围。但是,我仍然不明白this
上述代码的范围是什么,也不明白我将如何重写这段代码以消除编译器警告。
Q1:有人可以为我澄清一下范围this
是什么吗?
Q2:有人可以提供一些代码片段来说明如何重写上述内容以消除编译器警告(我假设this
必须消除使用)?
TIA。