Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Everything declared in a constructor function's <code>prototype</code> is shared by all instances of that constructor function. If you define functions in the constructor function, then each instance gets its own copy of the function, which wastes memory (and could potentially cause problems if you compare properties between two instances later).</p> <p>Also, in your example the functions declared in the constructor function are private to the scope of the function. They cannot be called as member methods on instances. For that you would need to assign them to properties of the object:</p> <pre><code>MyObject = functon() { // ... this.myMethod = function() { // ... }; } </code></pre> <p>Douglas Crockford has a good write-up of prototypical inheritance that is definitely worth checking out: <a href="http://javascript.crockford.com/prototypal.html" rel="noreferrer">Prototypical Inheritance in JavaScript</a>.</p> <p><strong>UPDATE: Brief Prototype Summary</strong></p> <p>When you create a new object using a constructor function, the value of the function's <code>prototype</code> property is assigned as the new object's <em>prototype object</em>. (Yes, the names are confusing!) This is a lot like assigning a superclass in a class-based language (but not quite! Read Crockford's page!)</p> <pre><code>// MyObject constructor function: MyObject = function() { this.a = 1; } // Define an object to use as a prototype. var thePrototype = { b: 2 }; // Assign thePrototype as the prototype object for new instances of MyObject. MyObject.prototype = thePrototype; // Create an instance of MyObject. var x = new MyObject(); // Everything in thePrototype is available to x. console.log(x.b); // x's prototype is a reference to thePrototype, so updating it affects x. thePrototype.c = 3; console.log(x.c); // Setting properties on x always sets them *on x*, even if the property is // defined on the prototype: x.b = 0; y = new MyObject(); console.log(x.b); console.log(y.b); </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