google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Hàm JavaScript & Biểu thức so trùng: Vài ví dụ cơ bản Bài viết này cung cấp vài ví dụ mẫu JavaScript về cách thức sử dụng hàm và biểu thức so trùng trong ngôn ngữ lập trình JavaScript. Một bài viết hướng dẫn sử dụng JavaScript rất hữu ích dành cho người mới học.

Hãy xem thêm các bài viết khác về hàm và biểu thức so trùng rất hữu ích trên jsB@nk bạn nhé:

- Bảng tham khảo phương thức và hàm trong JavaScript
- Các hàm JavaScript dựng sẵn phổ biến
- Các ví dụ mẫu về hàm trong JavaScript
- Các hàm so trùng JavaScript dựng sẵn


Nhãn: hàm JavaScript, biểu thức so trùng, ví dụ cơ bản, hàm và biểu thức

Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

Lets start with a short quiz. What is alerted in each case?:

01//Question 1:
02function foo(){
03    function bar() {
04        return 3;
05    }
06    return bar();
07    function bar() {
08        return 8;
09    }
10}
11alert(foo());
12 
13//Question 2:
14function foo(){
15    var bar = function() {
16        return 3;
17    };
18    return bar();
19    var bar = function() {
20        return 8;
21    };
22}
23alert(foo());
24 
25//Question 3
26alert(foo());
27function foo(){
28    var bar = function() {
29        return 3;
30    };
31    return bar();
32    var bar = function() {
33        return 8;
34    };
35}
36 
37//Question 4:
38function foo(){
39    return bar();
40    var bar = function() {
41        return 3;
42    };
43    var bar = function() {
44        return 8;
45    };
46}
47alert(foo());

If you didn't answer 8, 3, 3 and [Type Error: bar is not a function] respectively, read on... (actually read on anyway ;-) )

What is a Function Declaration?

A Function Declaration defines a named function variable without requiring variable assignment. Function Declarations occur as standalone constructs and cannot be nested within non-function blocks. It's helpful to think of them as siblings of Variable Declarations. Just as Variable Declarations must start with "var", Function Declarations must begin with "function".

e.g.

1function bar() {
2    return 3;
3}

ECMA 5 (13.0) defines the syntax as
function Identifier ( FormalParameterListopt ) { FunctionBody }

The function name is visible within it's scope and the scope of it's parent (which is good because otherwise it would be unreachable)

1function bar() {
2    return 3;
3}
4 
5bar() //3
6bar  //function

What is a Function Expression?

A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via Functions Expressions can be named or anonymous. Function Expressions must not start with "function" (hence the parentheses around the self invoking example below)

e.g.

01//anonymous function expression
02var a = function() {
03    return 3;
04}
05 
06//named function expression
07var a = function bar() {
08    return 3;
09}
10 
11//self invoking function expression
12(function sayHello() {
13    alert("hello!");
14})();

ECMA 5 (13.0) defines the syntax as
function Identifieropt ( FormalParameterListopt ) { FunctionBody }

(though this feels incomplete since it omits the requirement that the containing syntax be an expression and not start with "function")

The function name (if any) is not visible outside of it's scope (contrast with Function Declarations).

So what's a Function Statement?

Its sometimes just a pseudonym for a Function Declaration. However as kangax pointed out, in mozilla a Function Statement is an extension of Function Declaration allowing the Function Declaration syntax to be used anywhere a statement is allowed.  It's as yet non standard so not recommended for production development

About that quiz....care to explain?

OK so Question 1 uses function declarations which means they get hoisted...

Wait, what's Hoisting?

To quote Ben Cherry's excellent article: "Function declarations and function variables are always moved ('hoisted') to the top of their JavaScript scope by the JavaScript interpreter".

When a function declaration is hoisted the entire function body is lifted with it, so after the interpreter has finished with the code in Question 1 it runs more like this:

01//**Simulated processing sequence for Question 1**
02function foo(){
03    //define bar once
04    function bar() {
05        return 3;
06    }
07    //redefine it
08    function bar() {
09        return 8;
10    }
11    //return its invocation
12    return bar(); //8
13}
14alert(foo());

But...but...we were always taught that code after the return statement is unreachable

In JavaScript execution there is Context (which ECMA 5 breaks into LexicalEnvironment, VariableEnvironment and ThisBinding) and Process (a set of statements to be invoked in sequence). Declarations contribute to the VariableEnvironment when the execution scope is entered. They are distinct from Statements (such as return) and are not subject to their rules of process.

Do Function Expressions get Hoisted too?

That depends on the expression. Let's look at the first expression in Question 2:

1var bar = function() {
2    return 3;
3};

The left hand side (var bar) is a Variable Declaration. Variable Declarations get hoisted but their Assignment Expressions don't. So when bar is hoisted the interpreter initially sets var bar = undefined. The function definition itself is not hoisted.

(ECMA 5 12.2 A variable with an initialzier is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.)

Thus the code in Question 2 runs in a more intuitive sequence:

01//**Simulated processing sequence for Question 2**
02function foo(){
03    //a declaration for each function expression
04    var bar = undefined;
05    var bar = undefined;
06    //first Function Expression is executed
07    bar = function() {
08        return 3;
09    };
10    // Function created by first Function Expression is invoked
11    return bar();
12    // second Function Expression unreachable
13}
14alert(foo()); //3

Ok I think that makes sense. By the way, you're wrong about Question 3. I ran it in Firebug and got an error

Try saving it in an HTML file and running it over Firefox. Or run it in IE8, Chrome or Safari consoles. Apparently the Firebug console does not practice function hoisting when it runs in its "global" scope (which is actually not global but a special "Firebug" scope - try running "this == window" in the Firebug console).

Question 3 is based on similar logic to Question 1. This time it is the foo function that gets hoisted.

Now Question 4 seems easy. No function hoisting here...

Almost. If there were no hoisting at all, the TypeError would be "bar not defined" and not "bar not a function". There's no function hoisting, however there is variable hoisting. Thus bar gets declared up front but its value is not defined. Everything else runs to order.

1//**Simulated processing sequence for Question 4**
2function foo(){
3    //a declaration for each function expression
4    var bar = undefined;
5    var bar = undefined;
6    return bar(); //TypeError: "bar not defined"
7    //neither Function Expression is reached
8}
9alert(foo());

What else should I watch out for?

Function Declarations are officially prohibited within non-function blocks (such as if) . However all browsers allow them and interpret them in different ways.

For example the following code snippet in Firefox 3.6 throws an error because it interprets the Function Declaration as a Function Statement (see above) so x is not defined. However in IE8, Chrome 5 and Safari 5 the function x is returned (as expected with standard Function Declarations).

1function foo() {
2    if(false) {
3        function x() {};
4    }
5    return x;
6}
7alert(foo());

I can see how using Function Declarations can cause confusion but are there any benefits?

Well you could argue that Function Declarations are forgiving - if you try to use a function before it is declared, hoisting fixes the order and the function gets called without mishap. But that kind of forgiveness does not encourage tight coding and in the long run is probably more likely to promote surprises than prevent them. After all, programmers arrange their statements in a particular sequence for a reason.

And there are other reasons to favour Function Expressions?

How did you guess?

a) Function Declarations feel like they were intended to mimic Java style method declarations but Java methods are very different animals. In JavaScript functions are living objects with values. Java methods are just metadata storage. Both the following snippets define functions but only the Function Expression suggests that we are creating an object.

1//Function Declaration
2function add(a,b) {return a + b};
3//Function Expression
4var add = function(a,b) {return a + b};

b) Function Expressions are more versatile. A Function Declaration can only exist as a "statement" in isolation. All it can do is create an object variable parented by its current scope. In contrast a Function Expression (by definition) is part of a larger construct. If you want to create an anonymous function or assign a function to a prototype or as a property of some other object you need a Function Expression. Whenever you create a new function using a high order application such as curry or compose you are using a Function Expression. Function Expressions and Functional Programming are inseparable.

1//Function Expression
2var sayHello = alert.curry("hello!");

Do Function Expressions have any drawbacks?

Typically functions created by Function Expressions are unnamed. For instance the following function is anonymous, today is just a reference to an unnamed function:

1var today = function() {return new Date()}

Does this really matter? Mostly it doesn't, but as Nick Fitzgerald has pointed out debugging with anonymous functions can be frustrating. He suggests using Named Function Expressions (NFEs) as a workaround:

1var today = function today() {return new Date()}

However as Asen Bozhilov points out (and Kangax documents) NFEs do not work correctly in IE < 9

Conclusions?

Badly placed Function Declarations are misleading and there are few (if any) situations where you can't use a Function Expression assigned to a variable instead. However if you must use Function Declarations, it will minimize confusion if you place them at the top of the scope to which they belong. I would never place a Function Declarations in an if statement.

Having said all this you may well find yourself in situations where it makes sense to use a Function Declaration. That's fine. Slavish adherance to rules is dangerous and often results in tortuous code. Much more important is that you understand the concepts so that you can make your own informed decisions. I hope this article helps in that regard.

Comments are very welcome. Please let me know if you feel anything I've said is incorrect or if you have something to add.

See also ECMA-262 5th Edition sections 10.5, 12.2, 13.0, 13.2

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web