Functions of JavaScript

Source: Internet
Author: User

Just started to learn JS, it is not accustomed to the use of its functions, such as a function inside will be nested a function, for the function to create the scope of the variable is also very confused, this syntax and JAVA too much difference, for this, read the "JavaScript Advanced Programming" The relevant content in this book, in Google access to relevant information, and here to make a summary

Creation of functions
//This is the most common way to createfunction sum(sum1,SUM2){  returnNum1+Num2;}//Assign a function to a variable, you need to call SUM (10,10)varSum= function(NUM1,NUM2){  returnNum1+Num2;};//The function created in this way is poorly read//It is not recommended to use this methodvarSum= New Function("NUM1","Num2","return NUM1 + num2");
Parameters

When it comes to functions, the first unavoidable topic is the parameters. In JS, the function of the parameter transfer method is similar to JAVA, all by copying the value of the variable method to pass. Variables are generally divided into basic variables (Boolean, int, etc.) and reference variables (objects). The copy of the basic variable is to copy the value directly to the corresponding variable, and the copy of the reference variable is to copy the address of the variable to the corresponding variable, and the next two examples will help to understand.

//In this example, ChangeNumber receives a args variable, which is a basic type///Then modify args in the function to see if this change will affect the value of the external Num//From the result, the parameter for the basic type of replication is only to copy its value, will not modify the original valuevarNum= 9;function ChangeNumber(args){Args= 8;}ChangeNumber(num);Alert(num);               //result is 9//In this example, the parameter we passed in is an Array object//Modify the value of the first element of an array to see if it affects the outer array//Through the results we can see that the external Array will have an impact. varArray= New Array();array[0]= 9;function Changearray(arr){arr[0]= 8;}Changearray(array);Alert(array[0]);          //result is 8
function is an object

In Java, often hear is a sentence is: "In the Java World, nowhere to object", in JS, this sentence is also set up. So is the function also an object? The answer is yes. As an object, you should have independent properties and methods, and then introduce the properties and methods of the object under Function.

  • The
  • This property
    This is a keyword in JavaScript.
    It represents an internal object that is automatically generated when the function is run and can only be used inside the function. Because the function is used in different situations, this represents a different object, but there is a general principle that this refers to the object that called the function.
    With an example we can better understand this concept

    var  name =   "window"   function  getname  () { var  name =    alert  (this . name )              }  getname  ()  //result is window   
  • Arguments Property
    In the JS function, for the number and type of parameters passed is not limited, so it seems a bit unfettered, then, how does it do this? Arguments played a big role. Arguments is an Array-like object that contains all the arguments passed in the function, and we can access the parameters at the specified position by arguments[i].

    functionadd(num1,num2){  alert(arguments[0]+arguments[1]);}add(1,2);               // 结果为 3

    Arguments in addition to this function, there is an important method: Callee, this property points to the function object, we can use this example to feel the role of callee, but also by the way to understand the phrase: "function is an object, function name is a pointer"

    ///First, this is a recursive functionfunction factorial(num){  if(num<=1){    return 1;  }Else{    returnNum* factorial(num-1);  }}//Call procedure to place factorial nullvarTruefactorial= factorial(Ten);Factorial= function(){  return 0;}Alert(truefactorial(5));     //ResultAlert(factorial(5));         //result is 0///from which we can see that factorial is a pointer to a function//So var truefactorial = factorial (10) is the function address assigned to Truefactorial//When the factorial function changes the content, the address that the truefactorial points to is not affected//Such writing may make the result error, and will inevitably make the function name and functions of the coupling///Then callee comes in handy.function factorial(num){  if(num<=1){    return 1;  }Else{    returnNum*arguments.callee(num-1);    }}

    Thinking:

From the above example, we should also consider whether there is a concept of overloading in JS?

    • Prototype property
      Each function we create has a prototype (prototype) attribute, which is a pointer to an object, and the purpose of this object is to include properties and methods that can be shared by all instances of a particular type. As in the following example:
      "' JavaScript
      function person () {}
      Person.prototype.name = "Nicholas";
      Person.prototype.age = 29;
      Person.prototype.job = "Software Engineer";
      Person.prototype.sayName = function () {
      alert (this.name);
      };

var person1 = new Person ();
Person1.sayname (); "Nicholas"

var person2 = new Person ();
Person2.sayname (); "Nicholas"
Alert (Person1.sayname = = Person2.sayname); True
```

When a function is created, a prototype property is created for the function according to a specific set of rules, which points to the prototype object. By default, all prototype objects will automatically have a construct (constructor) property that contains a pointer to the function where the prototype property is located. When an instance is created, there is a pointer to the constructor in this instance, which we call [[Prototype]]. We can use the following diagram to understand this passage:

Although there is [[Prototype]] this pointer, but we do not have access to it, but we can use isprototypeof to determine whether there is such a relationship between objects.

alert(Person.prototype.isPrototypeOf(person1));      // truealert(Person.prototype.isPrototypeOf(person2));      // true

A new method, called Object.getprototypeof, is added to Ecmascipt 5, which returns the value of [[Prototype]]. For example:

alert(Object.getPrototypeOf==Person.prototype);  // truealert(Object.getprototypeOf(person1).name);       // "Nicholas"

When you want to use the Name property of Person1, the search process is like this: first, the compiler asks "Person1 have the name attribute?" No The compiler then asks, "Does the Person1 prototype have a name attribute?" If so, return to "Nicholas".
Based on the search process above, we can understand the following code:

function  Person(){} Person.prototype.name = "Nicholas"; Person.prototype. Age  =  in; Person.prototype.Job  = "Software Engineer"; Person.prototype.Sayname = function(){  Alert( This.name);};varPerson1= New  Person();varPerson2= New  Person();Person1.name = "Greg";Alert(Person1.name);         //"Greg"Alert(Person2.name);         //"Nicholas"
  • Call and Apply Methods
    Both of these functions invoke a specific function in a particular scope, and actually equal the value of the this object in the body of the function.
  • Apply
    The Apply method receives two parameters, one is the scope in which the function is run, and the other is the parameter array. Where the parameter array can be an instance of an array, or it can be an arguments object.

     function sum(NUM1,NUM2){   returnNum1+Num2;  } function CallSum1(NUM1,NUM2){  return sum.Apply( This,Arguments;         //Incoming arguments object}function callSum2(NUM1,NUM2){  return sum.Apply( This,[NUM1,NUM2]);   //Incoming array}Alert(CallSum1(Ten,Ten));                          //Alert(callSum2(Ten,Ten));                          //
  • Pager
    The call method is the same as the scope of the Apply method, and they differ only in how the parameters are received. For call, the first parameter, the this value, does not change, except that the rest of the arguments are passed directly to the function.

    functionsum(sum1,sum2){return+ num2;}functioncallSum1(num1,num2){  returnsum.call(this,num1,num2);}alert(callSum(10,10));                      // 20
  • function Extension function scope
    The following example changes the scope of a function by using the call method.

    window.Color = "Red";varO= {Color:"Blue"};function GetColor(){  Alert( This.Color);}Saycolor();             //red;Saycolor.Pager( This);    //RedSaycolor.Pager(window);  //RedSaycolor(o);            //Blue
  • Bind method
    I personally think there is no difference between bind and call and apply methods. or by looking at an example to see how it's viewed.
    "' JavaScript
    Window.color = "Red";
    var o = {color: "Blue"};

function Saycolor () {
alert (This.color);
}
var objectsaycolor = Saycolor.bind (o);
Objectsaycolor (); Blue
```

Functions 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.