Search This Blog

Friday, November 2, 2012

Difference between function and method in javascript

Every function in JavaScript has a number of attached methods, including toString()call(), and apply() (remember that every function in JavaScript is an object).
Functions stand on their own (there is an alert() function, for example), while methods are functions inside an object's dictionary, and we invoke them through the object reference

Example:
function foo()
{
    alert(
'x');
}
alert(foo.toString());


------------------------

fn.call and fn.apply


fn.call(function, [thisObject, [argument1, ..., argumentN]]) is equivalent to function.call(thisObject, argument1, ..., argumentN)
fn.apply(function, [thisObject, [argumentsArray]]) is equivalent to function.apply(thisObject, argumentsArray)

Examples:
function foo(a, b) { return (this*a)-b }
fn.call(foo, 5, 6, 7) == 23
foo.call(5, 6, 7) == 23
fn.apply(foo, 5, [6, 7]) == 23
foo.apply(5, [6, 7]) == 23
  1. if (typeof fn == "undefined" ) var fn = {};
  2. fn.call = function call(fn /*, [thisp, [arg1, ..., argN]]*/) { return Function.prototype.call.apply(fn, Array.prototype.slice.call(arguments).splice(1, arguments.length)) };
  3. fn.apply = function apply(fn, thisp, args) {
  4. if ( args ) args.splice(0, 0, thisp);
  5. return Function.prototype.call.apply(fn, args)
  6. };

No comments:

Post a Comment