Note that there are some explanatory texts on larger screens.

plurals
  1. POJavaScript: Creating an object generically from its type and calling its constructor
    primarykey
    data
    text
    <p>Say there's a JavaScript object with a childType property, which is an object constructor, and you want to write a generic addChild method. It needs to create an instance of this.childType, and invoke its constructor, passing whatever arguments were passed into addChild. </p> <p>To be clear, the point is for each collection to create child objects itself, using the inherited generic addChild method and its known childType, not to validate the type of passed-in child objects.</p> <p>I didn't think this would be hard to do, but I've tried various things and only failed so far.</p> <p><strong>UPDATE:</strong></p> <p>I've updated the <a href="http://plnkr.co/edit/XrsGkwGBXT3vyCpylI6i" rel="nofollow">demo plunk</a> with the best solution I know of so far, and included some comments about the issue in the code. The failed attempts discussed below are no longer there. This solution requires all potential chold objects to have a 'new Agnostic constructor', so it's still not ideal. Further thoughts are most welcome.</p> <hr> <p>I know this line is wrong, for two reasons:</p> <pre><code>var child = new this.childItemType.call(args); </code></pre> <p>First is that I think some sort of 'this' needs to be passed to the call function, and I don't see what it'd be there.</p> <p>Second is probably a result of the first, the error reported in the browser:</p> <pre><code>Uncaught TypeError: function call() { [native code] } is not a constructor </code></pre> <p>I think this should be doable, but the syntax for creating that child object from this.childType and passed arguments escapes me so far. Can someone point out the missing brain cell here?</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.
 

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