JS function type (i)

Source: Internet
Author: User

First, the function type

1.1 in JS, each of these functions is an instance of the function type. And, like all other types, have properties and methods. Because the function is an object, the function name is actually a pointer to the function object. is not bound to a function, the function is usually defined using the function declaration syntax (function declaration).

function sum (num1,num2) {   return num1 + num2  }

This is similar to the way the following function expressions are declared (function expression declarations)

var function (sum1,sum2) {    return NUM1 + num2}

When declaring a function using a function expression, it is not necessary to use the function name, as shown above, to refer to the function by the variable sum.

The last way to define a function is a functions constructor, which can receive any number of arguments, but the last parameter is always considered a function body, and the previous parameter enumerates the parameters of the new function. As follows

var New Function ("Num1", "num2", "return NUM1 + num2"); // Not recommended

Technically, this is a function expression, but it is not recommended because this syntax results in parsing two of times of code.

A function is an object, and a function name is a pointer. Because the function name is just a pointer to a function, the function name is no different from the variable that contains the pointer to the object. In other words, a function may have multiple names.

function sum (num1,num2) {   return num1 + num2;}alert (sum (10,10))//var anthorsum = Sum;alert (anthorsum (10,10))//null; alert ( Anthorsum (10,10))//

The above code first defines a function named sum (), then declares the variable anthorsum and sets it equal to sum, (note: Using the function name without parentheses is to access the function pointer, not the calling function.) Anthorsum and Sum point to the same function at this point, so even if sum is set to NULL, Anthorsum can still be called normally.

1.2 No Overloads

Imagining function names as pointers also helps to understand why there is no concept of function overloading in JS.

function Addsum (NUM1) {   return num1 +  {}function  addsum (num1) {    return NUM1 + $  var//

This example declares two functions with the same name, and the result is that the following function overrides the previous one. The above code is actually no different from the following code

var addsum =  function  (NUM1)       {return NUM1 +  function  (NUM1) {   return NUM1 + $  }var//  -

As you can tell, when you create a second function, you actually overwrite the variable that references the first function.

1.3 function declarations and function expressions

In fact, when the parser loads data in the execution environment, the function declaration and function expression are not treated equally, and the parser first reads the function declaration and makes it available before executing any code. As for a function expression, you must wait until the parser executes to the line of code where it resides before it is actually parsed.

Alert (sum (10,10))//function  sum (num1,num2) {  return NUM1 +  num2;}

The above code is fully functional because the parser reads and adds the function declaration to the execution environment before the code begins execution by means of a process called a function declaration promotion. When the code is evaluated, the JS engine declares the function the first time and places it at the top of the source tree. So even if the code that declares the function calls its code, the JS engine can lift the function declaration to the top. If you change a function declaration to an equivalent function expression, an error will be caused during execution

Alert (sum (10,10))var sum =  function  (num1,num2) {  return NUM1 + num2;}

The reason for the above code error is that the function is in an initialized statement, not a function declaration. In other words, before executing a statement to a function, the variable sum does not hold a reference to the function, and because the first line of code will be an error, it will not actually execute to the next line.

You can also use function declarations and function expressions at the same time

var function sum () {}

1.4 Functions as values

Since the function name in JS itself is a variable, the function can be used directly as a value. That is, not only can you pass a function to another function like passing a parameter, but you can return the function as the result of another function.

function callsomefunction (somefunction,someargument) {    return  someFunction (someargument);}

This function receives two parameters, the first parameter is a function, the second argument is a value passed to the function, and then it can be passed as the following example.

function add10 (num) {    return num + ten;} var  RESULT1 = callsomefunction (add10,10//function  getgreeting (name) {     return ' Hello ' + name}var result2 = callsomefunction (getgreeting, ' Toms '//  Hello,toms

The Callsomefunction function here is the same, that is, no matter what function is passed in the first parameter value, it will return the result after the first argument, to access the function's pointer without executing the function, do not take the following two parentheses. So the above function passes ADD10 and getgreeting instead of their function returning the result.

Of course, you can return another function from one function. For example, suppose you have an array of objects, we want to sort on an array based on an object property, and the comparison function passed to the arrays sort () method receives two parameters, that is, the value to compare. However, we need a way to indicate which property to sort by. To solve this problem, you can define a function. It receives a property name and then creates a comparison function based on the property name. Here is the definition of the function

functionceretecomparisonfunction (PropertyName) {return function(object1,object2) {varValue1 =Object1[propertyname]; varvalue2 =Object2[propertyname]; if(Value1 <value2) {            return-1; } Else if(Value1 >value2) {            return1; } Else{            return0;    }    };} 

This function looks a bit complicated, but in fact it is simply a function nested in another function, and the inner function is preceded by a return operator, after the internal function receives the PropertyName parameter, it will use square bracket notation to get the value of the given property, Once you have obtained the desired attribute value, it is very simple to define the comparison function. The above function can be used in the following example

var data = [{name: "Zachary", Age:28},{name: "Nicholas", age:29}];d Ata.sort (createcomparisonfunction ( "name"); alert (data (//Nicholasdata.sort (createcomparisonfunction ("Age")); Alert (data (//Zachary

Here, we create an array of two objects, each containing a Name property and an age property, and by default the sort method invokes the ToString () method of each object to determine their order, but the resulting results are often not in accordance with the human mind habit. Therefore, we call the comparison function returned by the createcomarsionfunction ("Age") method, which is sorted according to the object's attribute.

1.5 Function Internal Properties

Inside the function, there are two special objects, arguments and this, where arguments is a class array object that contains all the parameters of the passed function, although the main purpose of arguments is to save the function arguments, but this object also has a property called callee. This property is a pointer to the function that owns the arguments object

function factorial (num) {    if(num <= 1) {      return 1;     Else {      return num * factorial (n-1)    }}

The definition of the factorial function generally uses recursive algorithm, as shown above, in the function has a name, and the name will not become the case, so the definition is not a problem, but the problem is that the function of the execution and the name factorial tightly coupled, in order to eliminate this tightly coupled phenomenon, You can use Arguments.callee as follows.

function factorial (num) {    if(num <= 1) {      return 1;     Else {      return num * Arguments.callee (n-1)    }}

In this rewritten function, there is no reference to the function name, so that the recursive invocation can be done normally, no matter what name the function uses.

var truefactorial =function() {    return 0 ;} Alert (truefactorial (/////0

Here, the variable truefactoraial obtains the value of the factorial, actually holds the pointer to the function in another location, and then we assign a simple function that returns 0 to the factorial variable, if, as in the original factorial (), The call to Truefactorial () will return 0 without using Arguments.callee (), but after releasing the coupling state between the code and the function name in the function body, truefactorial () can still return the factorial normally, as for factorial () , he is now just a function that returns 0.

Another special object inside the function is the environment object that This,this refers to as the function is executing, or the This value (the This object refers to window when the function is called at the global scope of the Web page).

Window.color = "Red"; var o = {color: "Blue"}; function Saycolor () {    alert (this//redo.saycolor =// 

JS function type (i)

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.