Note that there are some explanatory texts on larger screens.

plurals
  1. PODefining methods via prototype vs using this in the constructor - really a performance difference?
    primarykey
    data
    text
    <p>In JavaScript, we have two ways of making a "class" and giving it public functions. </p> <p>Method 1:</p> <pre><code>function MyClass() { var privateInstanceVariable = 'foo'; this.myFunc = function() { alert(privateInstanceVariable ); } } </code></pre> <p>Method 2:</p> <pre><code>function MyClass() { } MyClass.prototype.myFunc = function() { alert("I can't use private instance variables. :("); } </code></pre> <p>I've read numerous times people <a href="https://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-in-the-constructor">saying</a> that using Method 2 is more efficient as all instances share the same copy of the function rather than each getting their own. Defining functions via the prototype has a huge disadvantage though - it makes it impossible to have private instance variables. </p> <p>Even though, in theory, using Method 1 gives each instance of an object its own copy of the function (and thus uses way more memory, not to mention the time required for allocations) - is that what actually happens in practice? It seems like an optimization web browsers could easily make is to recognize this extremely common pattern, and actually have all instances of the object reference <em>the same</em> copy of functions defined via these "constructor functions". Then it could only give an instance its own copy of the function if it is explicitly changed later on.</p> <p>Any insight - or, even better, <em>real world experience</em> - about performance differences between the two, would be extremely helpful.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload