Question

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.

Était-ce utile?

La solution

...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()

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top