Files
codeql/javascript/ql/src/Declarations/InefficientMethodDefinition.qhelp
2018-08-02 17:53:23 +01:00

47 lines
1.2 KiB
XML

<!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>