Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>what about this : </p> <pre><code>var Foo = (function() { // "private" variables var _bar; // constructor function Foo() {}; // add the methods to the prototype so that all of the // Foo instances can access the private static Foo.prototype.getBar = function() { return _bar; }; Foo.prototype.setBar = function(bar) { _bar = bar; }; return Foo; })(); </code></pre> <p>And now we have instantiation, encapsulation and inheritance.<br> But, there still is a problem. The <code>private</code> variable is <code>static</code> because it's shared across all instances of <code>Foo</code>. Quick demo : </p> <pre><code>var a = new Foo(); var b = new Foo(); a.setBar('a'); b.setBar('b'); alert(a.getBar()); // alerts 'b' :( </code></pre> <p>A better approach might be using conventions for the private variables : any private variable should start with an underscore. This convention is well known and widely used, so when another programmer uses or alters your code and sees a variable starting with underscore, he'll know that it's private, for internal use only and he won't modify it.<br> Here's the rewrite using this convention : </p> <pre><code>var Foo = (function() { // constructor function Foo() { this._bar = "some value"; }; // add the methods to the prototype so that all of the // Foo instances can access the private static Foo.prototype.getBar = function() { return this._bar; }; Foo.prototype.setBar = function(bar) { this._bar = bar; }; return Foo; })(); </code></pre> <p>Now we have instantiation, inheritance, but we've lost our encapsulation in favor of conventions : </p> <pre><code>var a = new Foo(); var b = new Foo(); a.setBar('a'); b.setBar('b'); alert(a.getBar()); // alerts 'a' :) alert(b.getBar()); // alerts 'b' :) </code></pre> <p>but the private vars are accessible : </p> <pre><code>delete a._bar; b._bar = null; alert(a.getBar()); // alerts undefined :( alert(b.getBar()); // alerts null :( </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. 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