Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript apply — Inheriting classes
    text
    copied!<p>The code below is adapted from <a href="https://stackoverflow.com/questions/422476/javascript-setting-methods-through-prototype-object-or-in-constructor-differenc/422535#422535">this answer</a></p> <pre><code> function MessageClass() { var self = this; this.clickHander = function(e) { self.someoneClickedMe = true; }; var _private = 0; this.getPrivate = function() { return _private; }; this.setPrivate = function(val) { _private = val; }; } ErrorMessageClass.prototype = new MessageClass(); function ErrorMessageClass() { MessageClass.apply(this, arguments); } var errorA = new ErrorMessageClass(); var errorB = new ErrorMessageClass(); errorA.setPrivate('A'); errorB.setPrivate('B'); console.log(errorA.getPrivate()); console.log(errorB.getPrivate()); </code></pre> <p>The original post did not have the <code>MessageClass.apply(this, arguments);</code> since the purpose was to show how inheritance can go wrong in Javascript. </p> <p>My question is, is saying: <code>ErrorMessageClass.prototype = new MessageClass();</code> <strong>before</strong> the ErrorMessageClass constructor has even been declared bad practice? My understanding is that calling undeclared identifiers like that causes a silent declaration to occur, with the result being placed on the global window object, which I understand is bad.</p> <p>Is this form:</p> <pre><code> function ErrorMessageClass() { MessageClass.apply(this, arguments); } ErrorMessageClass.prototype = new MessageClass(); </code></pre> <p>considered to be better practice? <a href="http://www.bennadel.com/blog/1514-Extending-Classes-In-Object-Oriented-Javascript.htm" rel="nofollow noreferrer">This link</a> shows the code written as it was originally above, which is why I even tried it. Does this blogger know something I don't (quite likely)?</p> <p><strong>EDIT</strong></p> <p>Lots of great info in the answers below, but I did want to highlight <a href="https://stackoverflow.com/questions/3887408/javascript-function-declaration-and-evaluation-order">this link</a> which really explains things perfectly</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