Вопрос

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.

Это было полезно?

Решение

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top