Note that there are some explanatory texts on larger screens.

plurals
  1. POjavascript apply on constructor, throwing "malformed formal parameter"
    primarykey
    data
    text
    <p>thanks to wonderful responses to <a href="https://stackoverflow.com/questions/1959040/possible-to-send-javascript-varargs">this question</a> I understand how to call javascript functions with varargs.</p> <p>now I'm looking to use <strong>apply with a constructor</strong></p> <p>I found some interesting information <a href="https://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply">on this post</a>.</p> <p>but my code is throwing errors</p> <p>attempt 1:</p> <pre><code>var mid_parser = new Parser.apply(null, mid_patterns); </code></pre> <p>error:</p> <pre><code>TypeError: Function.prototype.apply called on incompatible [object Object] </code></pre> <p>attempt 2: attempt 1:</p> <pre><code>var mid_parser = new Parser.prototype.apply(null, mid_patterns); </code></pre> <p>error:</p> <pre><code>TypeError: Function.prototype.apply called on incompatible [object Object] </code></pre> <p>attempt 2:</p> <pre><code>function Parser() { this.comparemanager = new CompareManager(arguments); } mid_patterns = [objA,objB,objC] var mid_parser = new Parser(); Parser.constructor.apply(mid_parser, mid_patterns); </code></pre> <p>error:</p> <pre><code>syntax_model.js:91: SyntaxError: malformed formal parameter </code></pre> <p>attempt 3:</p> <pre><code>var mid_parser = Parser.apply(null, mid_patterns); </code></pre> <p>error :</p> <pre><code>TypeError: this.init is undefined // init is a function of Parser.prototype </code></pre> <p>I have a workaround for the time being:</p> <pre><code>function Parser() { if(arguments.length) this.init.call(this,arguments); // call init only if arguments } Parser.prototype = { //... init: function() { this.comparemanager = new CompareManager(arguments); } //... } var normal parser = new Parser(objA,objB,objC); mid_patterns = [objA,objB,objC] var dyn_parser = new Parser(); dyn_parser.init.apply(dyn_parser, mid_patterns); </code></pre> <p>this works pretty well, but it's not as clean and universal as I'd like.</p> <p>is it possible in javascript to call a constructor with varargs?</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.
 

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