Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've got at least half a dozen implementations of various inheritance patterns lying around in my <code>dev/web/stuff</code> folder, but they are mostly toys.</p> <p>What I actually sometimes use is the following thin wrapper over JavaScript's default pseudo-class-based approach to make inheritance easier:</p> <pre><code>Function.prototype.derive = (function() { function Dummy() {} return function() { Dummy.prototype = this.prototype; return new Dummy; }; })(); </code></pre> <p>Example code:</p> <pre><code>function Pet(owner, type, name) { this.owner = owner; this.type = type; this.name = name; } Pet.prototype.toString = function() { return this.owner + '\'s ' + this.type + ' ' + this.name; }; function Cat(owner, name) { Pet.call(this, owner, 'cat', name); } Cat.prototype = Pet.derive(); var souris = new Cat('Christoph', 'Souris'); </code></pre> <p>Another interesting one is the following, which automatically adds factory methods to a proper prototypal approach:</p> <pre><code>var Proto = new (function() { function Dummy() {} this.clone = function() { Dummy.prototype = this; return new Dummy; }; this.init = function() {}; this.create = function() { var obj = this.clone(); this.init.apply(obj, arguments); return obj; }; }); </code></pre> <p>Example code:</p> <pre><code>var Pet = Proto.clone(); Pet.init = function(owner, type, name) { this.owner = owner; this.type = type; this.name = name; }; Pet.toString = function() { return this.owner + '\'s ' + this.type + ' ' + this.name; }; Cat = Pet.clone(); Cat.init = function(owner, name) { Pet.init.call(this, owner, 'cat', name); }; // use factory method var filou = Cat.create('Christoph', 'Filou'); // use cloning (the proper prototypal approach) var red = filou.clone(); red.name = 'Red'; </code></pre> <p>You've <a href="https://stackoverflow.com/questions/1404559/what-will-be-a-good-minimalistic-javascript-inheritance-method/1404697#1404697">already seen</a> my <a href="http://mercurial.intuxication.org/hg/js-hacks/raw-file/tip/class.js" rel="nofollow noreferrer">implementation of classes</a>.</p>
    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. 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