Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Methods that inherit via the prototype chain can be changed universally for all instances, for example:</p> <pre><code>function Class () {} Class.prototype.calc = function (a, b) { return a + b; } // Create 2 instances: var ins1 = new Class(), ins2 = new Class(); // Test the calc method: console.log(ins1.calc(1,1), ins2.calc(1,1)); // -&gt; 2, 2 // Change the prototype method Class.prototype.calc = function () { var args = Array.prototype.slice.apply(arguments), res = 0, c; while (c = args.shift()) res += c; return res; } // Test the calc method: console.log(ins1.calc(1,1,1), ins2.calc(1,1,1)); // -&gt; 3, 3 </code></pre> <p>Notice how changing the method applied to both instances? This is because <code>ins1</code> and <code>ins2</code> share the same <code>calc()</code> function. In order to do this with public methods created during construction, you'd have to assign the new method to each instance that has been created, which is an awkward task. This is because <code>ins1</code> and <code>ins2</code> would have their own, individually created <code>calc()</code> functions. </p> <p>Another side effect of creating methods inside the constructor is poorer performance. Each method has to be created every time the constructor function runs. Methods on the prototype chain are created once and then "inherited" by each instance. On the flip side of the coin, public methods have access to "private" variables, which isn't possible with inherited methods.</p> <p>As for your <code>function Class() {}</code> vs <code>var Class = function () {}</code> question, the former is "hoisted" to the top of the current scope before execution. For the latter, the variable declaration is hoisted, but not the assignment. For example:</p> <pre><code>// Error, fn is called before the function is assigned! fn(); var fn = function () { alert("test!"); } // Works as expected: the fn2 declaration is hoisted above the call fn2(); function fn2() { alert("test!"); } </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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