JavaScript 函数

 

  • 函数

     函数或者称之为方法,由执行一个特定任务的相关代码构成,函数可以包含零个或多个参数,并且可以返回一个任意的值。

// 函数声明
function foo() {}
// 命名函数表达式
var foo = function() {};

 

  • 函数调用
    • 没有返回值的函数调用
var greet = function( person, greeting ) {
var text = greeting + ", " + person;
console.log( text );
};
greet( "Rebecca", "Hello" ); // "Hello, Rebecca"
 
    • 有返回值的函数调用
var greet = function( person, greeting ) {
var text = greeting + ", " + person;
return text;
};
console.log( greet( "Rebecca", "Hello" ) ); // "Hello, Rebecca"
    • 返回值为一个函数的函数调用
var greet = function( person, greeting ) {
var text = greeting + ", " + person;
return function() {
console.log( text );
};
};
var greeting = greet( "Rebecca", "Hello" );
greeting(); // "Hello, Rebecca"

 

  • 立即调用的函数表达式
    在JavaScript中立即调用函数表达式是很常见的,这种模式的函数可以在创建之后立即执行。
(function() {
var foo = "Hello world";
})();

 

  • 函数作为参数
    在JavaScript中函数的地位是非常高,又被称之为一等公民,它可以分配给一个变量或者作为参数传递给另一个函数。
// 传递一个匿名函数作为参数
var myFn = function( fn ) {
var result = fn();
console.log( result );
};
myFn( function() {
return "hello world";
});
// 传递一个命名函数作为参数
var myFn = function( fn ) {
var result = fn();
console.log( result );
};
var myOtherFn = function() {
return "hello world";
};
myFn( myOtherFn );
posted @ 2013-08-14 08:46  M守护神  阅读(567)  评论(0编辑  收藏  举报