mirror of
https://github.com/github/codeql.git
synced 2026-03-06 23:56:48 +01:00
47 lines
1.2 KiB
XML
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>
|