JavaScript Object-Oriented Programming (4): Functions

Source: Internet
Author: User
In many languages, functions (Methods in Java) are very different from objects. A function is defined as an object action or global (like the main function in C ++ ). However, in JavaScript, the boundaries between functions and objects are not so obvious. 1. Function DefinitionJavaScript has many methods to define functions: function hello () {alert ("Hello! ");}
Var hello1 = function () {alert ("Hello! ");};
Var hello2 = new Function ("", "alert ('Hello! ');");
Hello ();
Hello1 ();
Hello2 (); the preceding three JavaScript function definition statements are provided. The first sentence is a common definition. It seems that it is not very different from other languages such as Java. This sentence defines a named function. According to the above example, the function name here is "hello. The second sentence is to assign a value to a variable after an anonymous function is defined, so this variable can be used to reference this anonymous function. These two statements seem to have the same effect, but they are different: the first sentence defines a name function, the second sentence defines an anonymous function. Although you can reference this anonymous function through this variable, it is actually anonymous. Their differences can be seen from the following:
hello(); 
hello1(); // error
function hello() { alert("Hello!"); }
var hello1 = function() { alert("Hello!"); };

The name function applies globally: You can use this function before definition. However, the definition of an anonymous function is backward. Like C/C ++, it must be defined before it can be used. That's why hello1 is incorrect. Then imagine why? The process of JavaScript interpretation is the same as that of HTML. Therefore, the anonymous function is equivalent to the definition of a variable. Therefore, the definition of this variable is not known during the interpretation and execution of the JavaScript interpreter, so an error occurs. However, the function is defined to scan the global.

The third statement is very interesting. It creates a Function class object. This constructor has two parameters: the first is the function parameter, and the second is the function body. Specifically, the following two function definitions are equivalent: function sayHelloTo (name ){
Alert ("Hello," + name );
}
Var sayHelloTo1 = new Function ("name", "alert ('hello, '+ name)"); this method of defining functions is not common, however, this statement shows interesting features: it means that you can use this constructor to dynamically construct a function at runtime! This is a feature not available in general languages. 2. Function ParametersJavaScript Functions are also quite flexible. They are not only defined in a variety of ways, but even have "strange" behavior in their parameters. JavaScript is a weak language, so it cannot detect your function parameter type, or even ensure that the number of parameters you pass in is consistent with the function definition. This requires some special detection.
function sum2(a, b) { 
        alert(a + b);
}
sum2(1); // NaN
sum2(1, 2); // 3
sum2(1, 3, 5); // 4
Let's look at this example. We only accept two parameter functions and can have any parameter during the call! However, it only uses the number that meets the condition, which is the first two parameters here. Therefore, when you pass in a parameter, JavaScript tries to add two numbers. The second parameter does not exist, so the returned value is NaN. In the third case, the number of real parameters is more than the number of form parameters. In this case, JavaScript only adds the first two parameters. Although it is not formal, it can be said that the JavaScript function parameter is an indefinite parameter, that is, you can input any parameter value. You can use the built-in arguments of the JavaScript function to traverse all input parameters. For example, the following code:
function sum() { 
        var total = 0;
        for(var i = 0; i < arguments.length; i++) {
                total += arguments[i];
        }
        alert(total);
}
sum(1, 2);
sum(1, 2, 3);
Arguments acts like an array, but it is not an array. You can use the typeof operator or call its constructor attribute. Here we need to note that arguments has a callee attribute and can call the function of arguments itself. That is to say, the function itself can be recursively called through this attribute. Therefore, even anonymous functions can be called recursively. For example:
Function sum (n ){
If (n <= 1 ){
Return 1;
}
Return n + arguments. callee (n-1); // recursively calls itself
}
Alert (sum (1, 100 ));
I think everyone will know the answer to this famous question. 3. functions are also objectsThink back to the third statement above, which strongly implies that a function is actually an object! As an object, a function should have all the features of the object: Adding properties, deleting properties, and returning values. Yes! JavaScript Functions are like this!
Function hello (){
Alert ("Hello! ");
}
Hello. name = "Tom"; // Add attributes
Alert (hello ["name"]);
Delete hello. name; // delete attributes
Alert (hello. name );
// Assign a value to a variable
Var hello1 = function () {alert ("hello1 ");};
Hello1 ();
// As an array element
Function show (x) {alert (x );}
Var arr = [show];
Arr [0] (5 );
// As a function parameter
Function callFunc (func ){
Func ();
}
Callfunc (function (){
Alert ("inner function .");
});
// Return value of the Function
Function show (){
Return function (n ){
Alert ("number is" + n );
};
}
Show () (10 );
Look! All functions that can be done by objects can be done! Functions in JavaScript are objects! Now we have started from arrays to objects and functions. These are basic concepts. We will further introduce the object-oriented features of JavaScript.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.