Skip to content Skip to sidebar Skip to footer

What Does This Usage Of Apply() Means In Javascript

Please, can someone tell me what does this.init.apply(this, arguments) do in the code below? I understand what apply() does in general, but in the context of the code below, what i

Solution 1:

apply is a member function of a function object. Suppose we have:

functionsaySomething(thing, anotherThing) {
    alert(this + " says " + thing + " and " + anotherThing);
}

Then we can use:

saySomething.apply(document, ["hello", "goodbye"]);

This calls the function and supplies the values of the array as arguments to the function. The first argument species the context of the function (or, what this equals when the function runs).

You should also be aware that arguments is a special variable that holds an array of all arguments passed to the function. So, here, this.init.apply(this, arguments) means that the init function is called and passed all the of arguments that were passed to the klass constructor.

In a real implementation, I think init would expect arguments. Consider how this would be done without apply:

var klass = function(arg1, arg2, arg3) {
    init(arg1, arg2, arg3);
}

klass.prototype.init = function(arg1, arg2, arg3) {}

If you wanted to add arg4 to init, you'd have add it in three places! By having klass transparently pass all its arguments to init, you make you code much less brittle.

Post a Comment for "What Does This Usage Of Apply() Means In Javascript"