以下JS:
(function() {
"use strict";
$("#target").click(function(){
console.log("clicked");
});
}());
收益率:
test.js: line 5, col 3, '$' is not defined.
当使用JSHint 0.5.5检测时。什么好主意吗?
以下JS:
(function() {
"use strict";
$("#target").click(function(){
console.log("clicked");
});
}());
收益率:
test.js: line 5, col 3, '$' is not defined.
当使用JSHint 0.5.5检测时。什么好主意吗?
当前回答
如果你正在使用一个相对较新的JSHint版本,通常首选的方法是在你的项目的根目录下创建一个.jshintrc文件,并将以下配置放在其中:
{
"globals": {
"$": false
}
}
这向JSHint声明$是一个全局变量,false表示它不应该被覆盖。
.jshintrc文件在真正旧的JSHint版本中不受支持(例如v0.5.5,就像2012年的原始问题一样)。如果你不能或不想使用.jshintrc文件,你可以在脚本文件的顶部添加这个:
/*globals $:false */
还有一个简写“jquery”jshint选项,在jshint选项页面上可以看到。
其他回答
下面是一个可以放在.jshintrc中的小列表 随着时间的推移,我将在这个列表中添加新的内容。
{
// other settings...
// ENVIRONMENTS
// "browser": true, // Is in most configs by default
"node": true,
// others (e.g. yui, mootools, rhino, worker, etc.)
"globals": {
"$":false,
"jquery":false,
"angular":false
// other explicit global names to exclude
},
}
你所需要做的就是在.jshintrc中设置"jquery": true。
根据JSHint选项引用:
jquery 这个选项定义了由jQuery JavaScript库公开的全局变量。
如果你正在使用IntelliJ编辑器,如WebStorm, PyCharm, RubyMine或IntelliJ IDEA:
在文件/设置/JavaScript/代码质量工具/JSHint的环境部分,单击jQuery复选框。
如果您正在使用IntelliJ编辑器,在
首选项/设置 Javascript 代码质量工具 JSHint 预定义的(在底部),单击Set
你可以输入任何东西,例如console:false,它也会把它添加到列表(.jshintrc)中——作为一个全局变量。
我不建议使用通常的“关闭JSHint全局变量”,而是建议使用模块模式来解决这个问题。它使你的代码“包含”并提供性能提升(基于Paul Irish的“关于Jquery的10件事”)。
我倾向于这样写我的模块模式:
(function (window) {
// Handle dependencies
var angular = window.angular,
$ = window.$,
document = window.document;
// Your application's code
}(window))
你可以获得其他性能好处(在这里解释更多):
When minifying code, the passed in window object declaration gets minified as well. e.g. window.alert() become m.alert(). Code inside the self-executing anonymous function only uses 1 instance of the window object. You cut to the chase when calling in a window property or method, preventing expensive traversal of the scope chain e.g. window.alert() (faster) versus alert() (slower) performance. Local scope of functions through "namespacing" and containment (globals are evil). If you need to break up this code into separate scripts, you can make a submodule for each of those scripts, and have them imported into one main module.