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
Summary. The apply() method invokes a function with a given this value and arguments provided as an array. The apply() method is similar to the call() method excepts that it accepts the arguments of the function as an array instead of individual arguments.
Call invokes the function and allows you to pass in arguments one by one. Apply invokes the function and allows you to pass in arguments as an array. Bind returns a new function, allowing you to pass in a this array and any number of arguments.
The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array. Return Value: It returns the method values of a given function.
The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With