what does this usage of apply() means in Javascript

javascript, jquery, web-applications

Solution

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

function saySomething(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.

Problem

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 is it doing in there? ``` var Class = function() { var klass = function() { this.init.apply(this, arguments); //I don't really get this bit... }; klass.prototype.init = function(){}; return klass; }; var Person = new Class; //Usage var someone = new Person; ``` I see a lot of people using it. I've got an idea of what it does but can't really put my hands on it so I need more light. I'm going up an extra level in JS, so I wanna know everything about it, not just the simple 'Hello world' level. Many thanks

Original source

Related problems