]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/no-prototype-builtins.md
import 8.23.1 source
[pve-eslint.git] / eslint / docs / src / rules / no-prototype-builtins.md
1 ---
2 title: no-prototype-builtins
3 layout: doc
4 rule_type: problem
5 ---
6
7
8
9 In ECMAScript 5.1, `Object.create` was added, which enables the creation of objects with a specified `[[Prototype]]`. `Object.create(null)` is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from `Object.prototype`. This rule prevents calling some `Object.prototype` methods directly from an object.
10
11 Additionally, objects can have properties that shadow the builtins on `Object.prototype`, potentially causing unintended behavior or denial-of-service security vulnerabilities. For example, it would be unsafe for a webserver to parse JSON input from a client and call `hasOwnProperty` directly on the resulting object, because a malicious client could send a JSON value like `{"hasOwnProperty": 1}` and cause the server to crash.
12
13 To avoid subtle bugs like this, it's better to always call these methods from `Object.prototype`. For example, `foo.hasOwnProperty("bar")` should be replaced with `Object.prototype.hasOwnProperty.call(foo, "bar")`.
14
15 ## Rule Details
16
17 This rule disallows calling some `Object.prototype` methods directly on object instances.
18
19 Examples of **incorrect** code for this rule:
20
21 ::: incorrect
22
23 ```js
24 /*eslint no-prototype-builtins: "error"*/
25
26 var hasBarProperty = foo.hasOwnProperty("bar");
27
28 var isPrototypeOfBar = foo.isPrototypeOf(bar);
29
30 var barIsEnumerable = foo.propertyIsEnumerable("bar");
31 ```
32
33 :::
34
35 Examples of **correct** code for this rule:
36
37 ::: correct
38
39 ```js
40 /*eslint no-prototype-builtins: "error"*/
41
42 var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");
43
44 var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);
45
46 var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");
47 ```
48
49 :::
50
51 ## When Not To Use It
52
53 You may want to turn this rule off if your code only touches objects with hardcoded keys, and you will never use an object that shadows an `Object.prototype` method or which does not inherit from `Object.prototype`.