启用no-prototype-builtins规则可强制拦截Object.prototype方法的直接调用,配置为"error"级别,并配合--fix自动修复为Object.prototype.method.call(obj)形式,确保对hasOwnProperty等7个内置方法的安全调用。

要让自动化Lint工具强制拦截对 Object.prototype 原型方法(如 hasOwnProperty、toString、valueOf 等)的直接调用,核心是启用并正确配置 ESLint 的 no-prototype-builtins 规则。
启用 no-prototype-builtins 规则
该规则是 ESLint 内置规则,无需额外安装插件。在项目根目录的 ESLint 配置文件(如 .eslintrc.js、.eslintrc.json 或 eslint.config.js)中,将规则设为 "error" 级别即可实现强制拦截:
- 在
.eslintrc.js中添加:
module.exports = {
rules: {
"no-prototype-builtins": "error"
}
};
- 若使用 Flat Config(ESLint v8.52+ 推荐格式),在
eslint.config.js中写为:
import eslint from "@eslint/js";
export default [
eslint.configs.recommended,
{ rules: { "no-prototype-builtins": "error" } }
];
明确受控的原型方法列表
该规则默认拦截以下 7 个常见 Object.prototype 方法的直接调用:
hasOwnPropertyisPrototypeOfpropertyIsEnumerabletoLocaleStringtoStringvalueOf-
__defineGetter__(已废弃,但仍被检查)
它不会误报 Array.prototype 或 Date.prototype 上的方法——只聚焦于 Object.prototype 的原始继承方法。
配合 --fix 自动修复(推荐)
启用规则后,运行 npx eslint . --fix 可自动将违规写法转换为安全调用形式:
- 修复前:
obj.hasOwnProperty("key") - 修复后:
Object.prototype.hasOwnProperty.call(obj, "key")
此修复方式确保:即使 obj 自身覆盖了 hasOwnProperty、或为 Object.create(null) 创建的无原型对象,调用依然有效且可预测。
与构建流程/CI 深度集成
仅本地配置不够,需确保拦截真正生效:
- 在
package.json的"scripts"中加入校验脚本:
"lint": "eslint \"src/**/*.{js,ts}\" --max-warnings 0"(--max-warnings 0表示警告也视为失败) - CI 流水线(如 GitHub Actions)中,在测试步骤前执行
npm run lint,失败即中断发布 - 编辑器中安装 ESLint 插件(如 VS Code 的 ESLint 扩展),实时标红提示,防患于未然

















