A brief talk on the usage _javascript technique of call (), apply () and bind () in JavaScript

Source: Internet
Author: User
Tags anonymous closure

A function in JavaScript is not only a language feature similar to the Java method, it can also exist as an object. This article will explore some of the special uses of functions in JavaScript, including call, apply, and bind three prototype methods.
first, the function of the foundation
A function in JavaScript is a language feature similar to a method in Java, but it can be defined independently of the class.

Functional programming: Because JavaScript supports anonymous functions, you can use functions as objects, so JavaScript not only supports procedural programming (object-oriented as well as procedural programming), it also supports functional programming.
Context

Each invocation of a function will have a special value-the context of this call-which is the value of the This keyword. If a function is mounted on an object as an attribute of an object, it is called the method of the object. When the function is invoked through this object, the object is the context of this call, the value of this function.

Note that this is a keyword, not a variable, nor is it a property name. JavaScript syntax is not allowed to assign a value to this.

A function is an object

The biggest difference between a function in JavaScript and a method in Java or a function in the C language is that a function in JavaScript is also an object. But that doesn't mean that all objects are functions. A function is a special object that contains executable code and can be called by other code.

Unlike a variable, the keyword this has no scope limitations, and nested functions do not inherit this from the function that called it. -If the nested function is called as a method, its value points to the object that called it. -If the nested function is called as a function, the value of this is not a global object (not in strict mode) is undefined (in strict mode).

Many people mistakenly assume that this will point to the context of the outer function of I when calling nested functions. If you want to access this value of this external function, you need to save the value of this to a variable that is in the same scope as the internal function. For example:

var o = {
 m:function () {
  var self = this;
  Console.log (this==o); True
  f ();
  
  function f () {
   Console.log (this = = O);//False,this value is a global object or undefined
   console.log (self = = O);/true
  }
   }
}

Closed Bag

JavaScript functions can be nested within other functions so that they can access any variable in the scope where they are defined. This means that JavaScript functions form a closure (closure), which gives JavaScript very strong programming power.

function as a value
in JavaScript, a function is not only a syntax, but also a value, that is, a function can be assigned to a variable, stored in the object's properties or an array of elements, as a parameter passed into another function, and so on.

Bind, call, apply
Each function contains a prototype attribute, which is a reference to an object called a "prototype object." Each function contains a different prototype object. When a function is used as a constructor, the newly created object inherits the property from the prototype object.

Function.prototype.call () and Function.prototype.apply ()

Call () and apply () can be viewed as a method of an object, calling a function indirectly by calling the form of the method. Their first argument is the parent object that is calling the function, which is the invocation context, which is used in the function body to obtain a reference to it. The Apply () method works the same as the call () method, except that the function is passed in a different way, and its arguments are placed in an array.

For example, call function f () in the form of object o and pass in two parameters, which can be used:

var o = {};

function f (A, B) {return
 a + b;
}

F.call (o, 1, 2);    The method of function f as O is to reset the context of function F
f.apply (o, [1, 2]);

To give an example, use the call method to invoke an anonymous function:

In the following example, in the For loop body, we create an anonymous function and then execute the anonymous function with each array element as the specified this value by calling the function's call method. The main purpose of this anonymous function is to add a print method to each array element object, which prints out the correct index number of each element in the array. Of course, it is not necessary to have the array element pass into that anonymous function as the this value (normal arguments can), in order to demonstrate the use of call.

var animals = [
 {species: ' Lion ', Name: ' King '},
 {species: ' Whale ', Name: ' Fail '}
];

for (var i = 0; i < animals.length i++) {
 (function (i) { 
  this.print = function () { 
   console.log (' # ' + i + ' + this.species + ': ' + this.name); 
  } 
  This.print ();
 }). Call (Animals[i], i);
}

Function.prototype.bind ()

Bind () is a new method in ES5, and the main function of this method is to bind a function to an object, as you can see from the name. When you invoke the bind () method on the function f () and then flee to an object o as a parameter, this method returns a new function: Invoking the new function (as in the function call) will invoke the original function f () as the method of O. For example:

function f (Y) {return
 this.x + y;
}

var o = {
 x:1
};

var g = F.bind (o); Call O.F (x) g (2) by calling G (x)
;/3

In fact, we can easily implement the bind () method:

Returns a function that invokes the method F () in O, passing all of its argument
function bind (f, O) {
 if (f.bind) return F.bind (o);//If the bind () method exists, use BIND ( Method
 else return function () {return
  f.apply (o, arguments);
 }


Second, function-type programming
JavaScript is not a functional programming language, but it can manipulate functions like manipulating objects in JavaScript, which means you can apply functional programming techniques to JavaScript.

Working with arrays using functions

Suppose there is an array, and the array elements are numbers, and we want to calculate the average and standard deviation of those elements.

var data = [1, 1, 3, 5, 5];
var sum = function (x, y) {return
 x + y;
};
var square = function (x) {return
 x * x;
};

var mean = data.reduce (sum)/data.length;
var deviations = Data.map (x => x-mean);

var StdDev = math.sqrt (Deviations.map (square). reduce (sum)/(DATA.LENGTH-1);
Higher order functions

A higher order function is a function that receives one or more functions as arguments and returns a new function. As an example:

Function not (f) {return
 function () {
  var result = f.apply (this, arguments);
  return!result;}
var even = function (x) {return
 x% 2 = 0) to
determine if x is an even number;

var odd = not (even);      A new function, the things done and even () opposite
[1, 1, 3, 5, 5].every (odd);   True, each function is odd

The function not () is a higher order function because it returns a new function that passes its arguments to F () and returns the logical non of the return value of F.

The above is about the use of JavaScript call (), apply (), bind (), I hope to help you learn.

Related Article

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.