Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, the first function has no relationship with an object instance of that <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_a_Constructor_Function" rel="noreferrer">constructor function</a>, you can consider it like a <em>'static method'</em>.</p> <p>In JavaScript functions are <a href="http://en.wikipedia.org/wiki/First-class_function" rel="noreferrer"><em>first-class</em></a> objects, that means you can treat them just like any object, in this case, you are only adding a property to the <em>function object</em>.</p> <p>The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/new_Operator" rel="noreferrer"><code>new</code></a> keyword, and the context within that function (the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/this_Operator" rel="noreferrer"><code>this</code></a> keyword) will refer to the actual object instance where you call it.</p> <p>Consider this example:</p> <pre><code>// constructor function function MyClass () { var privateVariable; // private member only available within the constructor fn this.privilegedMethod = function () { // it can access private members //.. }; } // A 'static method', it's just like a normal function // it has no relation with any 'MyClass' object instance MyClass.staticMethod = function () {}; MyClass.prototype.publicMethod = function () { // the 'this' keyword refers to the object instance // you can access only 'privileged' and 'public' members }; var myObj = new MyClass(); // new object instance myObj.publicMethod(); MyClass.staticMethod(); </code></pre>
 

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