Home / یک نکته زیبا در مورد تابع ها در جاوا اسکریپت

یک نکته زیبا در مورد تابع ها در جاوا اسکریپت


In JavaScript functions are first class citizens, like classes in OO languages.
You can define a function in the traditional way like this.
 
function eat(){ console.log("Eating"); }
 
You can invoke the eat() function even before you define it, as shown here.
 
eat();//Prints Eating
function eat(){ console.log("Eating"); }
 
Though JavaScript is an interpreted language, function definitions are run first, irrespective of where they are
placed in the code. So you can invoke a function even before you define it like the eat() function call.
You can also assign a function to a variable like this:
 
var eat = function(){ console.log("Eating"); }
Though eat is defined to be a variable, you can still invoke it like a normal function call: eat(). But what you have
to watch out for is that you cannot invoke the eat() function before defining the variable. The following code will
throw an error if the function is declared as an expression.
 
eat();//Uncaught TypeError: Property 'eat' of object [object DOMWindow] is not a function
var eat = function(){ console.log("Eating"); }
 
So what’s the use of assigning a function to a variable? You can pass the eat variable as an argument to other
functions, as shown in Listing 1-2.
Listing 1-2.  Functions as arguments
function work(arg){
arg();
}
work(eat);
work(function(){console.log("Coding");});
 
As shown in Listing 1-2, the work() function accepts an argument which can be a reference to another function.
We can then invoke the passed function using the arg() call. A function that accepts another function as an argument
is commonly referred as a Higher-order function.

JSON in JS
One of the most popular and widely-used features of JavaScript is the JavaScript Object Notation (JSON). It’s used to
represent a JavaScript object. It’s also used as a data format like XML. Here’s a JSON object.
var myBook = {
title : "Practical Ext JS4",
author:"Prabhu Sunderaraman",
publisher : "APress",
price : 49.99,
formats : ["e-book","paperback"],
order : function(){
console.log("Ordering " + this.title + " in Amazon");
}
};
 
The myBook variable is a JSON object with some properties. The formats is an array and order() is a function.



     RSS of this page