Rya*_*P13 2 javascript validation jquery jslint jshint
在JSHint中运行此代码时,我收到了几个"未定义"错误:
MERLIN.namespace('MERLIN.http');
MERLIN.http = function ($, window) {
'use strict';
// import dependencies
function request(config) {
if (!config || typeof config !== 'object') {
return;
}
// perform request
$.ajax({
type: config.type || 'GET',
url: config.url,
dataType: config.dataType,
data: config.data || {},
processData: config.process || false,
beforeSend: function () {
indicator(config.panel, config.indicator);
},
complete: function () {
indicator(config.panel, config.indicator);
},
success: function (resp) {
var callback = config.success || null;
if (typeof callback !== 'function') {
callback = false;
}
if (callback) {
callback.apply(this, [resp]);
}
},
error: function (xhr, textStatus, errorThrown) {
httpError({
xhr: xhr,
status: textStatus,
error: errorThrown,
panel: config.panel
});
}
});
};
function indicator(panel, type) {
if ((!panel || typeof panel !== 'string') || (!type || typeof type !== 'string')) {
return;
}
var indicatorType = (type === 'large') ? type = 'indicatorLarge' : type = 'indicatorSmall';
return $(panel).toggleClass(indicatorType);
};
function httpError() {
return this;
};
return {
request: request,
error: httpError
};
} (jQuery, this);
Run Code Online (Sandbox Code Playgroud)
我不确定为什么为'指示符'和'httpError'抛出未定义的错误以及为什么使用'return this'是一种潜在的严格违规行为.我知道我可以安全地忽略与命名空间相关的未定义错误,因为通用命名空间函数先前在单独的文件中定义.
它只是一个实用主义与严格验证的案例吗?
谢谢 :)
关于'indicator' is not defined.和类似的错误:JSHint源自JSLint,由Douglas Crockford编写.Crockford有一个关于在定义之前出现在源文本中的函数调用的事情,即使它是完全正确和合法的代码并且没有任何歧义.我实际上认为这是JSLint(和启用该错误时的JSHint)积极反对的一种情况 - 我想知道什么时候真正未定义,而不是根据Crockford的风格规则未定义.(不是我有意见.)
你可以通过移动的声明避免这些错误indicator,并httpError达到以上request,但比从JSHint虚假错误等,没有理由这样做.
关于错误return this;,我相信JSLint/JSHint告诉你你正在返回全局对象的方式,因为它期望以小写字母开头的函数只被称为函数而不是伪方法.为什么要httpError回来this?你调用它的方式this将是全局对象.
因此,虽然在这种情况下你正在返回全局对象是正确的,但你也可以完全虚假地得到那个错误.例如,此代码产生该错误:
var Foo = (function() {
"use strict";
function Foo() {
}
function bar() {
return this; // "ERROR: [8:16]: Strict violation."
}
Foo.prototype.bar = bar;
return Foo;
})();
Run Code Online (Sandbox Code Playgroud)
那里没有严格的违规行为.bar将返回this,如果我bar正确调用(例如,var f = new Foo(); f.bar();)将是通过Foo而不是全局对象创建的对象的实例.
如果我更改了该代码,以便我不帮助我的工具帮助我:
var Foo = (function() {
"use strict";
function Foo() {
}
Foo.prototype.bar = function() {
return this;
};
return Foo;
})();
Run Code Online (Sandbox Code Playgroud)
...错误消失了,因为JSLint/JSHint假设函数将被this设置为除全局对象之外的其他东西.但后来我的功能是匿名的,这不太理想.
但是,通过使函数名称以小写字母以外的其他内容开头,可以使JSLint/JSHint更高兴.例如,我通常的命名约定有效:
var Foo = (function() {
"use strict";
function Foo() {
}
function Foo$bar() {
return this;
}
Foo.prototype.bar = Foo$bar;
return Foo;
})();
Run Code Online (Sandbox Code Playgroud)
没有生成错误.名称Foobar,Foo_bar以及$bar所有工作.
| 归档时间: |
|
| 查看次数: |
1604 次 |
| 最近记录: |