gpt4 book ai didi

javascript - Object.prototypes 内置直接规则

转载 作者:行者123 更新时间:2023-11-30 11:10:40 24 4
gpt4 key购买 nike

当类型检查变量以防止应用程序崩溃时,我总是使用

var hasBarProperty = foo.hasOwnProperty("bar");

但是我最近添加了一个新的 linting 包,它在该行抛出一个错误,说下面的行更好

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");

当我点击错误时,它显示了我不完全理解的解释,

https://eslint.org/docs/rules/no-prototype-builtins?fbclid=IwAR30-Z0mV40SaIPn0rPNUuyh2J3qJcsb8pE5GhNhTtZUE-sbYfLBcLNTeuM

那么为什么第二个比第一个好呢?

谢谢

最佳答案

规则告诉你使用

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");

而不是

var hasBarProperty = foo.hasOwnProperty("bar");

因为如果 foo overridden hasOwnProperty,后者可能不可靠:

var foo = {
hasOwnProperty: function() {
return true;
}
};
console.log(Object.prototype.hasOwnProperty.call(foo, "bar")); // false
console.log(foo.hasOwnProperty("bar")); // true

关于javascript - Object.prototypes 内置直接规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com