JavaScript Functons 函数简介

Functions contain blocks of code that need to be executed repeatedly. Functions can take zero or more arguments, and can optionally return a value.

Functions can be created in a variety of ways, two of which are shown below:

1
2
3
4
5
      
      
// Function declaration.
function foo() {
// Do something.
}
1
2
3
4
5
      
      
// Named function expression.
var foo = function() {
// Do something.
};

Using Functions

1
2
3
4
5
6
7
8
      
      
// A simple function.
var greet = function( person, greeting ) {
var text = greeting + ", " + person;
console.log( text );
};
greet( "Rebecca", "Hello" ); // "Hello, Rebecca"
1
2
3
4
5
6
7
8
      
      
// A function that returns a value.
var greet = function( person, greeting ) {
var text = greeting + ", " + person;
return text;
};
console.log( greet( "Rebecca", "Hello" ) ); // "Hello, Rebecca"
1
2
3
4
5
6
7
8
9
10
11
12
      
      
// A function that returns another function.
var greet = function( person, greeting ) {
var text = greeting + ", " + person;
return function() {
console.log( text );
};
};
var greeting = greet( "Rebecca", "Hello" );
greeting(); // "Hello, Rebecca"

Immediately-Invoked Function Expression (IIFE)

A common pattern in JavaScript is the immediately-invoked function expression. This pattern creates a function expression and then immediately executes the function. This pattern is extremely useful for cases where you want to avoid polluting the global namespace with code – no variables declared inside of the function are visible outside of it.

1
2
3
4
5
6
7
      
      
// An immediately-invoked function expression.
(function() {
var foo = "Hello world";
})();
console.log( foo ); // undefined!

Functions as Arguments

In JavaScript, functions are "first-class citizens" – they can be assigned to variables or passed to other functions as arguments. Passing functions as arguments is an extremely common idiom in jQuery.

1
2
3
4
5
6
7
8
9
10
11
      
      
// Passing an anonymous function as an argument.
var myFn = function( fn ) {
var result = fn();
console.log( result );
};
// Logs "hello world"
myFn( function() {
return "hello world";
});
1
2
3
4
5
6
7
8
9
10
11
12
      
      
// Passing a named function as an argument
var myFn = function( fn ) {
var result = fn();
console.log( result );
};
var myOtherFn = function() {
return "hello world";
};
myFn( myOtherFn ); // "hello world"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值