Javascript:function type

Source: Internet
Author: User

In JavaScript, the function is actually an object. each of these functions is an instance of a function type and has properties and methods just like other types. Function declaration method:

// First: Use function declaration syntax definitions function sum (NUM1, num2) {    return num1 + num2;} // Second: Use function expressions to define functions var function (NUM1, num2) {    return num1 + num2;}; // The third type: constructors var New Function ("Num1", "num2", "return num1+num2");

Because a function is an object, the function name is actually a pointer to a function and is not bound to a function. The function name is not different from the other variables that contain the object pointer, which means that a function may have multiple names:

function sum (NUM1, num2) {    return num1 + num2;} Alert (sum);    // 3 var anothersum = Sum;alert (anothersum (//  7null; Alert (Anothersum (4, 5));    // 9

It is important to note that the sum = null sum variable is removed from the function, but anothersum () can still be called normally.

No overloads

There is no overloaded mechanism in JavaScript similar to the Java language.

function addnum (num) {    return num + 1;} function addnum (num) {    return num + 2;} var result = Add (0);    // 2

The above example declares two functions, and the result shows that the function that follows is covered by the previous function. The above code is equivalent to:

function addnum (num) {    return num + 1;} function addnum (num) {    return num + 2;} var result = Add (0);    // 2
function declarations and function expressions

When the JavaScript parser loads data into the execution environment, it first reads the function declaration and makes it available before executing any code, and as for the function expression, it must wait until the parser executes to the line of code it is in before it is actually interpreted.

Alert (SUM (1, 2)); function sum (NUM1, num2) {    return num1 + num2;}

The above code can execute normally. This is because before the code executes, the parser has read and added the function declaration to the execution environment through the process called function declaration promotion. when evaluating code, the JavaScript engine can also elevate function declarations to the top.

If you change the function declaration to the form of a function expression, you will cause an error during execution.

Alert (SUM (1, 2)); var function (NUM1, num2) {    return num1 + num2;};

The above code will run an error. Because the function is in an initialization statement, a reference to the function is not saved in the variable sum until the statement in which the function is located is executed.

function as a value

The function in JavaScript itself is a variable, so the function can also be used as a value. This means that a function can be passed to another variable as a parameter.

function sum (ADD1, arg) {    return  add1 (ARG);}

The sum function receives two parameters. The first is that the parameter is a function, and the second argument should be a value to pass to the function.

 //  Add1 perform add 1 operation  function   Add1 (num) { return  num + 1;}   var  result = SUM (add1, 2 //  3    SayHello (name) { return  "Hello," + name;}  var  result1 = SUM (SayHello, "World"  //  "Hello, world"  

Note : the sum () function here is generic, and returns the result of the function, regardless of what function the first argument passes in. sum (ADD1, 2), and sum (SayHello, "World"), are all passed the Add1 () method and the SayHell0 () method instead of performing the results they return.

You can return another function from one function. For example, the comparison function of the array's sort () method mentioned earlier requires that two parameters be passed in.

functioncreatecomparisionfunction (PropertyName) {return function(Obj1, obj2) {varValue1 =Obj1[propertyname]; varvalue2 =Obj2[propertyname]; if(Value1 <value2) {            return-1; } Else if(Value1 >value2) {            return1; } Else {            return0; }    };}

The above defines a function in which a function is nested, and the inner function receives the propertyname parameter, uses the square bracket notation to get the value of the given property, and then defines the collation based on the value.

var data = [{name: "Zhangsan", age:18}, {name: "Lisi", Age:19}];d Ata.sort (createcomparisionfunction ( "Name"); alert (data[0].name)    ; // Lisi Data.sort (Createcomparisionfunction ("age")); alert (data[0].name);    // Zhangsan
Function Internal Properties

Inside the function, there are two special objects: arguments and this.

Arguments

Arguments is a class array object that contains all the parameters passed into the function. Arguments is primarily used to hold function arguments, and in addition to a callee property, callee is a pointer to a function that has arguments objects.

Let's look at a factorial example:

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

This method of definition is not a problem, the disadvantage is that the function is run tightly coupled with the name factorial, in order to solve this problem, you can use Arguments.callee.

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

This will not affect the function's normal operation, regardless of the name of the reference function. For example:

var newfactorial =function  () {    return 0;} Alert (newfactorial (  factorial (5));    // 0
This

This refers to the environment object to which the function is executed.

Window.color = "Red"; var obj = {color: "Blue"}; function Saycolor () {    alert (this. color);} Saycolor ();      // "Red", this refers to the window object obj.saycolor = saycolor;     // "Blue", this refers to the Obj object

The value of this is not deterministic until the function is called, and this will refer to different objects during the run. When calling Saycolor (), this refers to the global object Window,this.color equivalent to Window.color, when the Saycolor is assigned to the Obj object and Obj.saycolor () is called. This refers to the Obj object, so the This.color is Obj.color.

Caller

ECMASCRIPT5 provides the properties of another function object: caller. It holds a reference to the function that called the current function, and if the current function is called in the global scope, the value is null.

function outer () {    inner ();} function inner () {    alert (inner.caller);} Outer ();

The code above will show the source of the outer () function. Because outer () calls inner (), Inner.caller executes outer ().

function Properties and methods

As mentioned earlier, functions in JavaScript are objects, so functions also have properties and methods. each function. Each function consists of two properties: length and prototype.

The Length property holds the number of arguments when the array is called, not the number of arguments defined at the time of the Declaration. For reference types in JavaScript,prototype is the real place where all of their instance methods are saved . Methods such as ToString () and valueof () are actually stored in the name of prototype, but are accessed through instances of their respective objects. In ECMAScript5, theprototype property is not enumerable , so using for-in cannot be discovered.

Each function contains two non-inherited methods: apply() and call() . Both of these methods call a function in a specific scope, which in effect sets the value of the this object in the body of the function.

Apply () method

The Apply () method receives two parameters: the first parameter is the scope in which the function is run, and the other is an array of arguments, which can be an instance of an array, or a arguments object.

functionsum (NUM1, num2) {returnNUM1 +num2;}functioncallSum1 (NUM1, num2) {returnSum.apply ( This, arguments);//Incoming Arguments}functioncallSum2 (NUM1, num2) {returnSum.apply ( This, [Num1, num2]);//incoming Array Object}alert (CALLSUM1 (1, 2));//3Alert (callSum2 (1, 2));//3
Call () method

The call () method works the same as the Apply () method, except that the parameters that are received differ. The first parameter is this, and the remaining parameters are passed directly.

function sum (NUM1, num2) {    return num1 + num2;} function callsum (NUM1, num2) {    return sum.call (This, NUM1, num2);} Alert (Callsum (1, 2));   // 3

In the case of the call () method, Callsum () must explicitly pass in each parameter, and the return value will be the same.

The biggest role of apply () and call () is to expand the scope in which the function is run.

 Window.color = "Red" ;  var  obj = {color: "Blue"  function   Saycolor () {alert ( this  .color);}             Saycolor ();  //  red   this ); //   red  saycolor.call (window); //      Red  saycolor.call (obj); //  blue  

In the above example, the Saycolor () method is defined in the global scope and is converted to in the global scope this.color window.color , so sayColor() the result is red. sayColor.call(this)and sayColor.call(window) explicitly call the function in the global scope, the result must be a hotspot. When run sayColor.call(obj) , the function's run environment becomes obj, and when executed sayColor() , it is this.color converted to obj.color , so the result is blue.

Bind () method

The bind () method creates an instance of a function whose this value is bound to the value passed to the bind () function.

Window.color = "Red"; var obj = {color: "Blue"}; function Saycolor () {    alert (this. color);} var objsaycolor = saycolor.bind (obj); Objsaycolor ();   // Blue

In the example above, Saycolor () calls bind () and passes in the object. The Objsaycolor () function was created. The This value of the Objsaycolor () function is obj, so even if objsaycolor () is lowered at the global scope, the result is blue.

Javascript:function type

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.