Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You want one instance to inherit the private state of another instance? Sure you can do this in JavaScript. First we need to define a utility function:</p> <pre><code>function weakBind(functable, prototype, state) { return function () { return functable.apply(this, Object.getPrototypeOf(this) === prototype ? [state].concat(Array.prototype.slice.call(arguments)) : arguments); }; } </code></pre> <p>Now we can create our base class as follows:</p> <pre><code>var Dog = (function () { function Dog() { if (this instanceof Dog) { // constructor code } else return Object.create(private); } var public = Dog.prototype, private = Object.create(public, { size: { value: "big" } }); public.saySize = weakBind(function (private) { return "I am a " + private.size + " dog."; }, public, private); return Dog; }()); </code></pre> <p>Now you can create a dog as follows:</p> <pre><code>var dog = new Dog; alert(dog.saySize()); // I am a big dog. alert(dog.size); // undefined </code></pre> <p>We can inherit the private state as follows:</p> <pre><code>var Chihuahua = (function () { function Chihuahua() { Dog.call(this); } var private = Dog(); Object.defineProperty(private, { size: { value: "small" } }); var public = Chihuahua.prototype = Object.create(Dog.prototype); public.saySize = weakBind(public.saySize, public, private); return Chihuahua; }()); </code></pre> <p>Now you can create a chihuahua as follows:</p> <pre><code>var chi = new Chihuahua; alert(chi.saySize()); // I am a small dog. alert(chi.size); // undefined </code></pre> <p>See the demo: <a href="http://jsfiddle.net/b3Eyn/" rel="nofollow">http://jsfiddle.net/b3Eyn/</a></p> <p><strong>Note:</strong> I wrote this answer just to show that it's possible to inherit private state in JavaScript. However I would advise you not to use this pattern. If you design your code well then you won't need to inherit private state in the first place.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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