Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think you're probably running into the issue of how and when function declarations vs. step-by-step code (what the spec calls <em>statement code</em>) happen.</p> <p>Code like this will fail in the way you describe, for instance:</p> <pre><code>var obj = new Thingy("Fred"); function Thingy(name) { this.setName(name); } Thingy.prototype.setName = function(name) { this.name = name; }; </code></pre> <p>...because you're calling the constructor before adding the <code>setName</code> function to the prototype. Note that calling the constructor before its declaration is just fine, it's just because the constructor is using a function that's set up <em>later</em> by the statement code that there's a problem. The order in which the JavaScript interpreter will try to process that code is:</p> <ol> <li>Create the function <code>Thingy</code> and make it available to the scope.</li> <li>Execute the <code>var obj = ....</code> line, calling the constructor.</li> <li>Execute the constructor's code (which in this case throws an exception because there's no <code>this.setName</code> function).</li> <li>Execute the <code>Thingy.prototype.setName = ...</code> line. (If no exception had been thrown in the last step, that is.)</li> </ol> <p>These steps happen for each script block (first the function declarations are done, then the statement code is executed in order), and even though the above example is fairly obvious, when you start putting together pieces from various different locations, you can create this situation less obviously.</p> <p>The solution, obviously, is to make sure you're not constructing the object before you've set up the <code>setName</code> property:</p> <pre><code>function Thingy(name) { this.setName(name); } Thingy.prototype.setName = function(name) { this.name = name; }; var obj = new Thingy("Fred"); </code></pre> <p>...and again, the above is fairly obvious, but it's possible to create these situations rather less obviously in the real world.</p> <p>My suspicion is that this is what's happening in your case. It's easy to prove: Using a debugger like Firebug on Firefox, VS.Net or the Script Debugger for IE, Chrome's DevTools, etc., put a breakpoint on the <code>SystemList.prototype.refreshData = ...</code> line and a breakpoint on the line where you're doing your <code>new SystemList(...)</code> and see which one executes first.</p> <p>Here are a couple of fiddles demonstrating the issue: <a href="http://jsfiddle.net/nZ9Ts/" rel="noreferrer">This one</a> fails in the constructor, <a href="http://jsfiddle.net/uYWmu/" rel="noreferrer">this one</a> succeeeds.</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