Thursday, July 3, 2008

Passing arguments from method to method in JavaScript

For example, you have one function greeting() that accepts two string arguments only. And you have another function callAnotherFunction() that accepts only one argument which is a function. In order to pass arguments from method to method, JavaScript provide ideal apply() and call() to deal with this scenario.



function greeting(name, str) {
alert(str + ", " + name);
}

function callAnotherFunction(method) {
method.apply(null, arguments); // arguments refer to ["John", "Good morning"]
alert(arguments.length); // arguments refer to method
}

callAnotherFunction(function() {greeting("John", "Good morning")});

The significant point in this example is arguments in callAnotherFunction(method). It means differently in the same function. In method.apply(null, arguments), it refers to the arguments that passed from method. And in alert(arguments.length), it refers to method itself, not its arguments.

These example might not make sense to some people but it very useful when you want to pass arguments from method to method.

Hope this help.



1 comment:

Sergey said...

Outsourcing to Eastern Europe has a range of advantages due to its attractive cost-to-quality ratio. I would recommend checking out this article to learn more about Python development companies in Poland.