Question

I'm studying apply and I am trying to understand why the code I am studying only passes one parameter to apply.

I first define Quo:

var Quo = function(string) {
  this.status = string;
};

Next I define get_status:

Quo.prototype.get_status = function() {
  return this.status;
};

I define statusObject:

var statusObject = {
  status: 'yo!'
};

And this is where I am lost:

var status = Quo.prototype.get_status.apply(statusObject);
// status is 'yo!'

According to the documentation "Apply Calls a function with a given this value and arguments provided as an array." You can see in the case, using apply I pass only a single parameter, which I believe is defining "this". Can you clear up what exactly is happening in this method, why apply is necessary, and why in this case I can only pass one param to the method, when it states two are needed. Thank you.

Was it helpful?

Solution

apply sets the context of the function being applied to the object provided in the first parameter.

var o;
function baz(a, b, c) {
  //do stuff
}

o = {
  foo: 'bar'
};

baz.apply(o);
//this is o
//a is undefined
//b is undefined
//c is undefined

If an array is passed as the second parameter, the parameters will be set based off the values in the array:

baz.apply(o, [1,2,3]);

//this is o
//a is 1
//b is 2
//c is 3

The second parameter in apply is optional, however call is typically used for settings context:

//these do the same thing
baz.call(o);
baz.apply(o);

//this is how they're different
baz.call(o, 1, 2, 3);
baz.apply(o, [1, 2, 3]);

OTHER TIPS

It doesn't state that two are needed:

fun.apply(thisArg[, argsArray])

notice how argsArray is in brackets, it is optional.

What is happening on your call, is that your statusObject is passed as the this argument to your get_status function.

This means that when get_status executes and does return this.status it is in essence returning statusObject.status.

Apply is useful for many reasons, one of which is to invoke methods dynamically. I can pass the string name of a method in the object to be invoked like so:

methods = {
    init: function(message) {
        alert(message);
    }
};
function executeFunc(method) {
    methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}

//now I can call like this:
executeFunc('init', 'Hey there, this is a message');

An example of this can be found in my jQuery Plugin skeleton on GitHub

apply takes one argument, the object to use as this, followed by the arguments if any.

If the function takes no arguments, e.g. you have function f() { ... }, you don't need to pass any arguments, so you can call f.apply(someObject);.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top