0

I was trying out a sample code for apply() from Mozilla Developer Network (https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)

The code I write is as below:-

function Person( first, last ) {
    this.first = first;
    this.last = last;
}

Person.prototype.fullName = function() {
    return this.first+"; "+this.last;
};

var p1 = new Person( "Junaid", "Kirkire" );
var p2 = new Person( "Aditya", "Shanker" );

Person.prototype.toString = function() {
    return "Name " + this.first;
};

function trivialNew( constructor, ...args ) {
    var o = {};
    constructor.apply( o, ...args );
    return o;
};

var p3 = trivialNew( Person, "Junaid", "Kirkire" );

I am getting a SyntaxError on the line constructor.apply(). Can anyone help me out with this? Thanks.

JunaidKirkire
  • 878
  • 1
  • 7
  • 17

1 Answers1

3

...args is not valid JavaScript syntax. It's MDN's way of saying "This is where your arguments go"

(So, replace that with your actual arguments)

For more information, check the MDN documentation on Function.prototype.apply()

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Thanks. I thought this was JS way of specifying arbitrary number of arguments. I think the code should be:- var p3 = trivialNew( Person, [ "Junaid", "Kirkire" ] ); and the trivialNew function should be:- function trivialNew( constructor, args ) { var o = {}; constructor.apply( o, args ); return o; }; – JunaidKirkire Feb 12 '14 at 07:45
  • That should work, yes. or: `trivialNew(Person, "Junaid", "Kirkire", "x", "y", "z", "etc");` and `constructor.apply(o, arguments);` ([`arguments` doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments)) – Cerbrus Feb 12 '14 at 07:59