pages tagged jsspwhittonhttps://spwhitton.name//tag/js/spwhittonikiwiki2015-11-18T17:09:12ZJavaScript inheritance idiomshttps://spwhitton.name//blog/entry/inheritance/2015-11-18T17:09:12Z2014-11-30T08:54:00Z
<p>If you don’t need to run a constructor function to make your new object,
you can call <code>Object.create()</code>:</p>
<pre><code> var a = {a: 1};
// a ---> Object.prototype ---> null
var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
</code></pre>
<p>I think that this is what Douglas Crockford is trying to do
<a href="http://javascript.crockford.com/prototypal.html">here</a> with versions of
JavaScript that don’t have the relatively new <code>Object.create()</code>.</p>
<p>If you want your new object to be a kind of class, that is, a
constructor function that inherits from some other constructor function,
this is a readable way of doing so:</p>
<pre><code>function ChildClass (...) {
// call the parent class constructor to give `this`
// all the properties and methods its parent class has
ParentClass.call(this, ...);
// then code that makes the child different from the parent:
// may well override (some of) what the parent class
// constructor just did
}
ChildClass.prototype = new ParentClass;
</code></pre>
<p>These idioms need to be made more complex to work with <a href="http://flipclockjs.com/">at least
some</a> jQuery plugins. Perhaps <code>jQuery.proxy()</code>
is all that’s needed.</p>
<p>Sources:
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain#With_Object.create">1</a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#More_flexible_constructors">2</a></p>