我认为问题在于您使用this 而不是在方法内部。以下代码
/*global jQuery */
var myObj = {
myNethod: function displayMegaDropDown() {
"use strict";
var ts = jQuery(this),
liMegaPosition = ts.position(),
divMegaOffset = {
top: liMegaPosition.top + ts.height(),
left: liMegaPosition.left
};
ts.find("div").offset(divMegaOffset);
ts.addClass("hovering");
}
};
或者这个
/*global jQuery */
function displayMegaDropDown(t) {
"use strict";
var ts = jQuery(t),
liMegaPosition = ts.position(),
divMegaOffset = {
top: liMegaPosition.top + ts.height(),
left: liMegaPosition.left
};
ts.find("div").offset(divMegaOffset);
ts.addClass("hovering");
}
不会给你任何错误或警告。
已更新:另外一个版本非常接近您的原始版本,也没有错误或警告:
/*global jQuery */
var displayMegaDropDown = function () {
"use strict";
var ts = jQuery(this),
liMegaPosition = ts.position(),
divMegaOffset = {
top: liMegaPosition.top + ts.height(),
left: liMegaPosition.left
};
ts.find("div").offset(divMegaOffset);
ts.addClass("hovering");
};
UPDATED 2:我觉得这个问题很有意思。所以我浏览了ECMAScript standard。我在“Annex C (informative) The Strict Mode of ECMAScript”中找到了以下内容(请参阅 HTML 版本 here 更好):
如果在严格模式代码中评估 this,则 this 值为
不强制到一个对象。 null 或 undefined 的 this 值不是
转换为全局对象,原始值不转换
包装对象。通过函数调用传递的 this 值
(包括使用 Function.prototype.apply 和
Function.prototype.call) 不会强制传递这个值到
对象(10.4.3、11.1.1、15.3.4.3、15.3.4.4)。
我想这是 JSLint 错误的原因。
当然,如果您关闭严格模式,代码将不再有错误:
/*global jQuery */
/*jslint sloppy: true */
function displayMegaDropDown() {
var ts = jQuery(this),
liMegaPosition = ts.position(),
divMegaOffset = {
top: liMegaPosition.top + ts.height(),
left: liMegaPosition.left
};
ts.find("div").offset(divMegaOffset);
ts.addClass("hovering");
}
更新 3: 似乎不可能在 function 语句 中使用 this,而在 中使用 this 的可能性函数表达式 似乎很多人都怀疑。今天,我收到了更多关于此的评论。所以我创建了一个非常简单的演示
/*jslint devel: true */
(function () {
'use strict';
function test() {
alert(this);
}
test();
}());
您可以测试here,在 IE9 中演示显示带有文本“[object Window]”的警报,而在当前版本的 Chrome 和 Firefox 上,您将看到“未定义”。
所以在函数语句中使用this 的问题不是“jslint 的事情”。这是您在开发 JavaScript 程序时应该考虑的真正问题。
我个人更喜欢使用函数表达式,几乎从不使用更多函数语句。我认为来自其他程序语言的人(也像我一样)一开始会尝试使用在您最喜欢的语言中很好的相同结构。直到后来才发现块中的变量定义不好(JavaScript 中没有块级范围)并且 函数语句 也不总是最好的选择。