我正在使用运行时功能分配来解决浏览器差异.但是对于不支持的浏览器,我想返回一个空函数,以便不抛出JavaScript错误.
但是,jslint抱怨空功能.什么是jslint快乐的方式来做到这一点?
空块.
$R.functionNull = function () {
// events not supported;
};
$R.Constructor.prototype.createEvent = (function () {
if (doc.createEvent) {
return function (type) {
var event = doc.createEvent("HTMLEvents");
event.initEvent(type, true, false);
$NS.eachKey(this, function (val) {
val.dispatchEvent(event);
});
};
}
if (doc.createEventObject) {
return function (type) {
var event = doc.createEventObject();
event.eventType = type;
$NS.eachKey(this, function (val) {
val.fireEvent('on' + type, event);
});
};
}
return $R.functionNull;
}());
Run Code Online (Sandbox Code Playgroud)
Fré*_*idi 10
您可以为函数添加一个实体并让它返回undefined:
$R.functionNull = function() {
// Events not supported.
return undefined;
};
Run Code Online (Sandbox Code Playgroud)
这保持了与"真正空"函数相同的语义,并且应该满足JSLint.
小智 5
对我来说,这最有效:
emptyFunction = Function();
console.log(emptyFunction); // logs 'ƒ anonymous() {}'
console.log(emptyFunction()); // logs 'undefined'
Run Code Online (Sandbox Code Playgroud)
它是如此之短,以至于我什至都不会将其分配给一个变量(当然,您也可以使用类似常量的变量“ EF”,它甚至更短,并且不需要附加的“()”括号)。只要在需要真正空函数的地方使用“ Function()”,它甚至都没有名称,甚至在您将其分配给变量时也是如此,这就是我的解决方案与Frédéric的行为之间的微小差异:
// --- Frédéric ---
emptyFunction = function() {
return undefined;
}
console.log(emptyFunction.name); // logs '"emptyFunction"'
// --- me ---
emptyFunction = Function();
console.log(emptyFunction.name); // logs '""' (or '"anonymous"' in chrome, to be fair)
Run Code Online (Sandbox Code Playgroud)