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.
Related
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
I'm new to JavaScript and making good progress. When I got to this part I was a little confused. Mostly the part that says "getName(first, last)". I don't quite get its purpose and what it does in detail. It wasn't declared with a "var" nor is it within the function, or "=" to anything. Also, I'm not to clear on the use of the parameters of the function. I'd really appreciate any help. I'm new to SE too and I'm loving it. Thanks in advance
var first = prompt("May I have the First Name");
var last = prompt("May I have the Last Name");
getName(first, last);
function getName(var1, var2) {
var x = var1 + " " + var2;
alert("The name is " + x);
}
Jarad
getName is a function in your JavaScript code which have two parameter var1 & var2. This function simply concatinate these two parameters with your text "The name is " and show in an alert message.
And the line getName(first,last); is calling your function getName() & passing two arguments first & last. You can pass any two arguments to this function and it will show it in an alert.
e.g: instead of using first & last, you can use the below code and see the result.
var x = 'Mr';
var y = 'Ayaz';
getName(x,y);
getName(first, last); is a function call. You're providing the function with two pieces of data (first name and last name) and instructing it to execute. The data you're providing it are called arguments, the identifiers in the function declaration are called parameters. The names do not need to match. Inside the function, the names it uses are the parameter names.
When you call
getName(first, last);
Control jumps to that function and the body (the part inside {} is executed).
Function declarations create a variable, with the same name as the function, in the current scope and are hoisted.
When using the jQuery "each" function, is there a way to pass arguments to the function that is called ?
something.each(build);
function build(vars) {
}
I know that I can simply do the following, but I was wondering if there is a way in which arguments can be passed directly.
something.each(function() {
build(vars);
);
You can accomplish the above using a closure. The .each function takes as an argument a function with two arguments, index and element.
You can call a function that returns a function that takes those two arguments, and store variables in there that will be referenced when the returned function executes because of JavaScript scoping behavior.
Here's an example:
// closureFn returns a function object that .each will call for every object
someCollection.each(closureFn(someVariable));
function closureFn(s){
var storedVariable = s; // <-- storing the variable here
return function(index, element){ // This function gets called by the jQuery
// .each() function and can still access storedVariable
console.log(storedVariable); // <-- referencing it here
}
}
Because of how JavaScript scoping works, the storedVariable will be reference-able by the returned function. You can use this to store variables and access in any callback.
I have a jsFiddle that also proves the point. Notice how the text output on the page is different than the HTML defined in the HTML pane. Look at how the function references the stored variable and appends that to the text
http://jsfiddle.net/QDHEN/2/
Here's the MDN page for closures for more reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
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.
//This is the function that will run every time a new item is added or the
//list is sorted.
var showNewOrder = function() {
//This function means we get serialize() to tell us the text of each
//element, instead of its ID, which is the default return.
var serializeFunction = function(el) { return el.get('text'); };
//We pass our custom function to serialize();
var orderTxt = sort.serialize(serializeFunction);
//And then we add that text to our page so everyone can see it.
$('data').set('text', orderTxt.join(' '));
};
full code is at http://demos.mootools.net/Dynamic.Sortables
var serializeFunction = function(*el*) { return el.get('text'); };
var orderTxt = sort.serialize(serializeFunction*(el)*);
compare the codes.
Is el being passed or not? what is going on???
I want to learn advanced parameter usage.
If not declaring functions like function name(parameter1, parameter2, parameter3...).
If not calling functions like name(parameter1, parameter2, parameter3...).
If parameters aren't variables.
If declaring functions like function(parameter1, parameter2, parameter3...).
If calling functions like variable(parameter1, parameter2, parameter3...).
If parameters are objects.
I'm interested.
You probably have a bookmark with the lessons in which I'm interested... please, share!!!
The value assigned to "serializeFunction" is actually an anonymous function, you can see it like a pointer or reference to a function, "el" is simply a declared input parameter that will be used then that function will be called.
Looking at the original code of the one that was posted, the call of the sort.serialize function, receives only the function as a parameter, the "serializeFunction" is not being invocated, it's only passed as an argument.
So, the serialize function that receives the reference of the function passed as a parameter it will be in charge of execute it internally.
This is a lambda expression like.
sort.serialize()
accept the function as parameter, not the value.
The first code is probably correct.
In JavaScript, functions are stored in variables just as any other value (as you see with serializeFunction), and sort.serialize only takes a reference to serializeFunction. Then serializeFunction is called from sort.serialize with the current element (el).
The second code would send an undefined value to the serializeFunction (since el has not been defined in that scope) which would throw an error. Even if el was defined, sort.serialize expects a reference to a function, not a value.