forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInefficientMethodDefinition.qhelp
More file actions
46 lines (34 loc) · 1.23 KB
/
InefficientMethodDefinition.qhelp
File metadata and controls
46 lines (34 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
Defining a method by assigning a closure to a property of the receiver object in the constructor
is inefficient, since a new closure is created for every instance. This wastes heap space and may
interfere with JIT compilation.
</p>
</overview>
<recommendation>
<p>
Assign the function to a property of the prototype object instead. That way, all instances share
the same closure.
</p>
</recommendation>
<example>
<p>
In the following example, constructor <code>Point</code> defines method <code>move</code> by creating
a new closure and storing it in the <code>move</code> property of each new instance. Consequently,
<code>p.move</code> and <code>q.move</code> are different methods.
</p>
<sample src="examples/InefficientMethodDefinition.js" />
<p>
It is better to instead define <code>move</code> on the prototype object <code>Point.prototype</code>
like this:
</p>
<sample src="examples/InefficientMethodDefinitionGood.js" />
</example>
<references>
<li>Mozilla Developer Network: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a>.</li>
</references>
</qhelp>