Function object methods function.apply() and function.call() basically do the same job, that is to invoke the function as if it was the method of a specified object so that the ‘this’ keyword within the function is treated as that object rather than the global object.
var x = 20;
function f(s)
{
alert(this.x + s);
}
f('!');
‘this’ keyword refers to global object by default, so the code above kicks out an alert of ’20!’. However, with
var x = 20;
var o = {x:40}; // o is an object with a property of x = 40
function f(s)
{
alert(this.x + s);
}
f('!');
f.call(o, '!'); // invoking function f as a method of object o, so this.x makes out to o.x = 40 thus an alert of '40!' instead of '20!'.
f.apply(o, ['!']); // does the same thing as f.call(o, '!')
‘this’ keyword is set to object o. You get the idea. The only difference you should pay attention to is that the second parameter supplied to f.apply() is an array.
You should also read:
- PHP: How to access a global variable inside a function without passing it?
- JavaScript: Split and Divide Text String by A Delimiter
- Work Around Zend Studio 5.5 PHP Class / Object / Method Auto-complete Problem
- JavaScript: Open or Redirect to Another Page / Site / Location
- PHP: True empty() function to check if a string is empty or zero in length


Facebook
Twitter
Google Plus