Passing argument from one function to another - javascript

I'm wondering if this way of passing an argument from one function to another (let's say from f1 to f2):
f1 = function(arg){
f2(arg);
}
f2 = function(arg){
//doing sth with passed argument
}
Is wrong? Or is it better/safer to always use the .apply() method, even if we're not passing an array?
To clarify- argument is passed only to f1, and only from f1 f2 is called.

No, it's not wrong.
Passing parameters through functions is one of the fundamental aspects of JavaScript as a language. It helps you take a complex application and break it down into manageable chunks for both clarity and maintainability.
.apply is useful when you want to call a function with a specific scope ( that's why the first parameter is this ) and it takes an array or array-like secondary parameter for arguments to be used within the function. The fact that it's an array/array-like makes no difference at all to you as a programmer or to the function that you're calling. There's nothing special about it, it's just the format that apply expects.

Nothing wrong about that at all. This happens all the time.
The only reason you should use apply() is if you need what it does, like changing the context (value of this) or passing an array as individual arguments. You aren't doing anything like that here, so there is absolutely no reason to make more complicated.

When you declare an argument in JavaScript it's treated just like a variable, and you can use it like any other variable: reassign values, pass it to another function, etc. .apply(this, arguments) is also possible, but it's not necessary unless you need to set the this of the called function or to pass an arbitrary number of arguments.

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.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>In this example the fullName method of person is <b>applied</b> on person1:</p>
<p id="demo"></p>
<script>
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe",
}
var x = person.fullName.apply(person1, ["Oslo", "Norway"]);
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
While if you use two function and call One in another:
function function_one() { function_two(); }
function function_two() {
//enter code here
}
Function parameters are the names listed in the function definition.
Function arguments are the real values passed to (and received by) the function.
Parameter Rules
JavaScript function definitions do not specify data types for parameters.
JavaScript functions do not perform type checking on the passed arguments.
JavaScript functions do not check the number of arguments received.
Parameter Defaults
If a function is called with missing arguments(less than declared), the missing values are set to: undefined
more information JavaScript you can read this link
https://developer.mozilla.org/it/docs/Web/JavaScript

Related

How does 'function1(data, function2)' work?

How does these code work ?
function output(a) {
console.log( "The function filter return " + a + "!");
}
x = function(data, fun) {
a = data;
fun(a);
};
theInput = " TEXT FROM INPUT ";
x(theInput, output);//The function filter return TEXT FROM INPUT !
I wrote it by mysels , and it works fine . But I don't understand how 'function1(data, function2)' run .
What is x?
It is a variable that holds a reference to a function with two parameters, data and fun.
Whats are you doing here?
x(theInput, output);
You call this function passing a string and a function. Yes, functions in JavaScript can be treated as any other object. Actually, they are also objects. So they can be stored to variables (store a reference to them), they can be passed as arguments to another function etc.
What is happening inside the body of the function that is stored in x ?
Initially, you assign the data to the variable called a and then you pass this as an argument to the function output. Then the function that is stored in output is called.
If there is one takeaway from this code snippet is the fact that you passed a function as an argument to another function. This is very important in JavaScript and it is associated with the nature of functions in JavaScript.
According to MDN:
In JavaScript, functions are first-class objects, i.e. they are
objects and can be manipulated and passed around just like any other
object. Specifically, they are Function objects.

In JavaScript, must bound parameters be in the anonymous function parameters?

Consider the code below, which works fine. It is the outcome of some debugging. It appears to work because I have inlcluded selectedRowNum not only in bind but it seems I am also required to include selectedRowNum as a parameter to the anonymous callback that is run by .end
Does this make sense? If I bind a variable, must I also include it as a param to the function I am binding it to?
for (var i = selectedRows.length; i--;) {
var selectedRowNum = selectedRows[i];
console.log('outer selectedRowNum');
console.log(selectedRowNum);
var url = urlbase + '/' + this.state.data[selectedRowNum].id;
request
.del(url)
.end(function(selectedRowNum, err, res) {
var data = this.state.data.slice();
data.splice(selectedRowNum, 1);
this.setState({data: data});
this.forceUpdate();
}.bind(this, selectedRowNum));
};
Yes, you need to.
The args values passed to the bind() will be prepended to the called functions param list, so you need to receive it in the target function as arguments.
A simple example will be
function x(p1, p2, p3) {
console.log(p1, p2, p3)
}
var fn = x.bind(window, 1);
fn(2, 3);
fn('a', 'b');
where we are passing an additional param 1 to the bind and when the binded function is called we are passing 2 and 3, now when we receive it in the method we need to have 3 parameters there.
How else do you expect to reference the bound value that you're trying to pass in?
function(selectedRowNum, err, res) { here selectedRowNum is simply a reference to the first argument that's passed in.
Well, technically the answer is no you don't need to. You could not list it as an argument, and refer to it as arguments[0]
Arguments are not absolutely required to be in the anonymous function declaration because you can access arguments via the arguments object as in arguments[0] and arguments[1].
But it is best to declare them as named arguments because it makes your code easier to read and write. If you don't declare them as named arguments in the anonymous declaration, then there is no symbolic name by which to refer to them and you are forced to use the arguments object to access them.
This is an important aspect of Javascript. Declaring named function arguments in a function declaration (whether anonymous or not) just gives you name by which you can refer to that specific argument. Since having a symbolic name is an important part of creating readable code, it is generally considered a good practice to follow.
When you use .bind() with arguments in addition to just the first argument, you are prepending more arguments to the actual function call. This will shift any other arguments later in the argument list. In order to access the correct argument, the anonymous function declaration must use the variables from the right spot in the argument list. If you don't include the extra variables that are added via .bind(), then your other arguments will be out of position and will have the wrong values.

When and why to use Call and Apply?

Firstly I came to know the difference between apply() and call().
function theFunction(name, profession) {
alert("My name is " + name + " and I am a " + profession + ".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]); // This call be called theFunction("Susan", "school teacher");, why use apply
theFunction.call(undefined, "Claude", "mathematician"); // This call be called theFunction("Claude", "mathematician");, why use call
From the above code, all the 3 function call displays the alert message.
What are the advantages/disadvantages of using apply and call, over normal function call, and when is it appropriate to use apply/call, please clarify me.
One more thing, what if the function is a prototype based function:
Function.prototype.theFunction = function(name, profession) {
alert("My name is " + name + " and I am a " + profession + ".");
}
Then how to call this function bu using apply or call. I tried this way:
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
but resulted in error.
"ReferenceError: theFunction is not defined"
As you have said it seems that you already know what these to functions apply() and call() actually do, but in terms of their uses, I'd say they are used mostly when you want to provide your function with a specific object of your own, as its this value in its context.
One of the most popular use of these two is to handle array-like objects like arguments objects in the function:
function(){
//let's say you want to remove the first parameter from the arguments object
//you can make sure that
console.log(arguments instanceof Array);//false
//as you see arguments is not an actual array object but it is something similar
//and you want slice out its value
var myparams = Array.prototype.slice.call(arguments, 1);
//here you have myparams without your first argument
console.log(arguments);
}
Let's go with another example. Say we have an independent function like:
function getName(){
console.log(this.name);
}
Now you can use it for any kind of JavaScript object that has a name attribute:
var myInfo = {
name: 'SAM'
};
now if you do:
getName.call(myInfo);
what it does is printing out the name attribute or you can try it on the function itself:
getName.call(getName);
which would print out the function's name ("getName") in the console.
But similar to my first example, it is usually used when you want to use functions that are not in the object's prototype chain. The other example of that could be:
//let's say you have an array
var myArray = [1 , 2];
//now if you use its toString function
console.log(myArray.toString());//output: "1,2"
//But you can use the Object toString funcion
//which is mostly useful for type checking
console.log(Object.prototype.toString.call(myArray));//output: "[object Array]"
This post gives a very detailed explanation of call() and apply().
TLDR;
Both call() and apply() are methods we can use to assign the this
pointer for the duration of a method invocation
The apply() method is identical to call(), except apply() requires an
array as the second parameter. The array represents the arguments for
the target method.
The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.
It Will Give You More Explaination
POST

How do I pass a method through another method without it being called, and pass a variable object into it?

Sorry for my last question. This is the question with better formatting.
I have a method that I am passing a method through :
method("my_passed_method()")
function method(passed_method){
eval(passed_method.replace('()', + '(' + obj + ')' );
}
But this returns :
SyntaxError: missing ] after element list
I'm assuming this is just some simple JSON syntactical error.
I think you probably want this:
method(my_passed_method)
function method(passed_method){
passed_method(obj);
}
Note that when you're calling method, you're passing in a function reference, not a string, and you're not calling my_passed_method (there are no () after it), you're just referring to it.
Within method, you call the function via the variable passed_method, because that variable contains a function reference.
In JavaScript, functions are first class objects. Variables can refer to them, you can pass them around, etc.
Here's a complete, self-contained example:
// The function we'll pass in
function functionToPass(arg) {
display("functionToPass's arg is: " + arg);
}
// The function we pass it into
function functionReceivingIt(func) {
func("foo");
}
// Do it
functionReceivingIt(functionToPass);
Live copy | source
The name of a method, is at the same time, your reference to that method object. The parentheses, optionally with parameters in between them, make javascript call that method. This means your code can be rewritten to:
method(my_passed_method)
function method(passed_method){
passed_method();
}
So, what's going on here?
When you pass in the name my_passed_method, the javascript engine will look what that name maps to, and find that it maps to a functio object.
Than, inside the function call of method, that object is assigned to the parameter name `passed_method. Than, putting parentheses after this name will make javascript try to execute that object, which is indeed possible because this object is a function, and just like any other type, functions are what we call first class citezens. You can treat the just like any other value by assigning them to variables and passing them around.
In Javascript functions are considered objects. You may pass them as parameters to other functions, as demonstrated below.
function something(x){
alert(x);
}
function pass(func){
pass2(func);
}
function pass2(func){
func("hello");
}
pass(something); //alerts hello
Demo:
http://jsfiddle.net/wBvA2/
eval is evil; or so they say. You don't need to pass the function as a string you can just pass the function itself and then use Function.call or Function.apply to pass the argument (or just call it directly):
method(my_passed_method);
function method(passed_method) {
passed_method(obj);
// OR: passed_method.call(window,obj);
}
The circumstances where eval are necessary are very rare.
Note that your code will evaluate obj as javascript, so the outputs may differ.

context to use call and apply in Javascript?

Guys can any one explain context to use call and apply methods in Javascript?
Why to use call and apply instead of calling a function directly ?
You use call or apply when you want to pass a different this value to the function. In essence, this means that you want to execute a function as if it were a method of a particular object. The only difference between the two is that call expects parameters separated by commas, while apply expects parameters in an array.
An example from Mozilla's apply page, where constructors are chained:
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}
function Food(name, price) {
Product.apply(this, arguments);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(name, price) {
Product.apply(this, arguments);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
What Product.apply(this, arguments) does is the following: The Product constructor is applied as a function within each of the Food and Toy constructors, and each of these object instances are being passed as this. Thus, each of Food and Toy now have this.name and this.category properties.
Only if you use call or apply you can modify the this context inside the function.
Unlike other languages - in JavaScript this does not refer to the current object - rather to the execution context and can be set by the caller.
If you call a function using the new keyword this will correctly refer to the new object (inside the constructor function)..
But in all other cases - this will refer to the global object unless set explicitly through call
You use .call() when you want to cause a function to execute with a different this value. It sets the this value as specified, sets the arguments as specified and then calls the function. The difference between .call() and just executing the function is the value of the this pointer when the function executes. When you execute the function normally, javascript decides what the this pointer will be (usually the global context window unless the function is called as a method on an object). When you use .call(), you specify exactly what you want this to be set to.
You use .apply() when the arguments you want to pass to a function are in an array. .apply() can also cause a function to execute with a specific this value. .apply() is most often used when you have an indeterminate number of arguments that are coming from some other source. It is often used too pass the arguments from one function call to another by using the special local variable arguments which contains an array of arguments that were passed to your current function.
I find the MDN references pages for .call() and .apply() helpful.
If you have experience with jQuery, you will know that most functions take use of the this object. For example, collection.each(function() { ... });
Inside this function, "this" refers to the iterator object. This is one possible usage.
I personally have used .apply() for implementing a queue of requests - I push an array of arguments into the queue, and when the time comes for executing it, I take an element, and pass it as the arguments for a handler function using .apply(), thus making the code cleaner then if having to pass an array of arguments as a first argument. That's another example.
In general, just keep in mind that those ways to call a function exist, and you may one day find them convenient to use for implementing your program.
If you have experience with Object Oriented Programming then call and apply will make sense if you compare it with inheritance and override the properties or method/functions of parent class from child class. Which is similar with call in javascript as following:
function foo () {
this.helloworld = "hello from foo"
}
foo.prototype.print = function () {
console.log(this.helloworld)
}
foo.prototype.main = function () {
this.print()
}
function bar() {
this.helloworld = 'hello from bar'
}
// declaring print function to override the previous print
bar.prototype.print = function () {
console.log(this.helloworld)
}
var iamfoo = new foo()
iamfoo.main() // prints: hello from foo
iamfoo.main.call(new bar()) // override print and prints: hello from bar
I can't think of any normal situation where setting the thisArg to something different is the purpose of using apply.
The purpose of apply is to pass an array of value to a function that wants those values as arguments.
It has been superseded in all regular everyday usage by the spread operator.
e.g.
// Finding the largest number in an array
`Math.max.apply(null, arr)` becomes `Math.max(...arr)`
// Inserting the values of one array at the start of another
Array.prototype.unshift.apply(arr1, arr2);
// which becomes
arr1 = [...arr2, ...arr1]

Categories

Resources