Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>So I have a class</p> </blockquote> <p>Javascript doesn't have classes. It has prototype inheritance that can emulate classes to a limited extent, but that isn't worthwhile purely for the sake of emulating classes. Much better to make optimal use of built–in language features rather than trying to make javascript emulate some other language.</p> <p>So you have a constructor...</p> <blockquote> <p>I have written a few functions which I can call like this:</p> <pre><code>var a = new A(); a.getSomething(); a.putSomething(); a.delSomething(); </code></pre> </blockquote> <p>Presumably those methods are all on A.prototype.</p> <blockquote> <p>And so on. Now I thought I'd organize it a bit So it wouldn't get too cluttered and would look like a bit more like this:</p> <pre><code>a.something.get(); a.something.put(); a.something.del(); </code></pre> </blockquote> <p>That isn't less cluttered (to me). I guess there is some common thing that is done by <em>something</em>, and that its <em>get</em>, <em>put</em>, etc. methods want to operate on <em>a</em> not on <em>something</em>. </p> <p>The value of <em>this</em> is set by the call, there is no other way to set its value other than with ES5 bind. So the method being called must have access to <em>a</em> somehow. Other answers show how to do that with a closure, but the consequence is that each instance must have its own <em>something</em> object and attached methods. </p> <p>The following is similar, but gets rid of the closure and puts the methods on <code>Something.prototype</code> for a bit of efficiency:</p> <pre><code>function A(name) { this.name = name; this.something = new Something(this); } function Something(that){ this.that = that; } Something.prototype.get = function() { return this.that.name; } Something.prototype.put = function(prop, value) { this.that[prop] = value; } var a = new A('a'); alert(a.something.get()); // a a.something.put('name', 'z'); alert(a.something.get()); // z </code></pre> <p>So you can have multiple <em>somethings</em>, each with different <em>put</em>, <em>get</em>, etc. methods. But the intervening <em>something</em> object is really just a device that uses more memory (probably a tiny amount) and requires an extra character. Simpler to keep the <em>something</em> methods on <code>A.prototype</code> and not have to type the extra dot (.).</p>
 

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