jslint错误:意外'在'.与undefined比较,或使用hasOwnProperty

hou*_*se9 20 javascript jslint

我有以下javascript函数未通过jslint检查

  function hasActiveX() {
    return ('ActiveXObject' in window);
  }
Run Code Online (Sandbox Code Playgroud)

jslint错误

Unexpected 'in'. Compare with undefined, or use the hasOwnProperty method instead.
Run Code Online (Sandbox Code Playgroud)

我应该忍受jslint错误,还是有更好的方法来确定ActiveXObject?我找不到跳过此检查的jslint标志?

Kas*_*tor 21

忽略错误."in"运算符在ECMA 262-5.1/June 2011 sec-11.8.7中明确定义

目前看来只有三种结果为'someProperty' in anObject这是一个:true,falseTypeError抛出异常.当它评估时true,肯定有'someProperty' in anObject.当它评估到false肯定没有'someProperty' in anObject.TypeError抛出a时肯定不会'someProperty' in anObject因为anObjectnull或者根本不是对象.这一切对我来说都很清楚.当我想知道对象是否有属性时,我不在乎该属性是对象自己的属性还是被继承,我不关心属性的值是什么,然后我只是寻找'someProperty' in anObject.

警告

警告:有些人会检查你,anObject.someProperty !== undefined但这并没有真正检查对象是否具有该属性.它在做什么是检查对象是否具有属性那个该属性的值是不是不确定的.有些人让你检查anObject.hasOwnProperty('someProperty');,但只会告诉你,如果对象具有属性继承它以某种方式.不相信我?请尝试以下方法:

console.log(document.body.tagName);
// BODY

console.log(document.body.hasOwnProperty('tagName'));
// false, it's inherited

console.log('tagName' in document.body);
// true, it does have the property

document.body.wobbles = undefined;
// new property added to document.body

console.log('wobbles' in document.body);
// true, it does have the property

console.log(document.body.wobbles !== undefined);
// false, the value really IS undefined
Run Code Online (Sandbox Code Playgroud)

我写了一篇关于"in"运算符的文章,该文章更详细.如果您想阅读它,请访问:http://matthewkastor.blogspot.com/2012/09/Unexpected--in---Compare-with-undefined--or-use-the-hasOwnProperty-method-instead.html底线是你应该忽略如果对象可能为null或不是对象,则此错误并在try catch块中包装.

function hasProperty(prop, obj) {
    try {
        return prop in obj;
    } catch(e) {
        return e;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ user577888是的,我知道为什么JSLint发出通知并且通知无法被禁止.上面的帖子解释了`in`的用法以及为什么可以安全地忽略它.简而言之,出于性能原因会出现警告.当您期望将属性直接分配给相关对象时,搜索整个原型链是没有意义的.在没有`hasOwnProperty`保护的情况下使用`in`并不是一个错误,这样做没有任何有害的副作用. (4认同)

Cᴏʀ*_*ᴏʀʏ 17

我认为JSLint要求你尝试:

function hasActiveX() {
    return window.hasOwnProperty('ActiveXObject');
}
Run Code Online (Sandbox Code Playgroud)

或者与"未定义"进行比较的其他建议:

return (typeof(window.ActiveXObject) != "undefined");
Run Code Online (Sandbox Code Playgroud)

就个人而言,我更喜欢前者.

看完评论之后,in如果JSLint停止抱怨它似乎真的很有用,否则我会尝试上面的选项2.

  • 调用`window.hasOwnProperty`将在*IE <= 8*上失败,因为全局对象不从`Object.prototype`继承(例如`Object.prototype.isPrototypeOf(window); // false`,你需要间接调用它,例如``Object.prototype.hasOwnPrototype.call(window,'ActiveXObject');`,但正如@missingno所说,不能保证该方法是一个自己的属性,它可以在原型链中声明全局对象(完全依赖于实现的东西),通常用于测试*host*属性,`in`运算符很有用...来吧jslint,不要伤害我们的代码:P (6认同)
  • typeof!== undef没用,只需检查属性是否未定义`return window.ActiveXObject!== undefined;` (2认同)