Usage of call (), apply (), bind () in javascript, applybind

Source: Internet
Author: User
Tags magic call

Usage of call (), apply (), bind () in javascript, applybind

Functions in JavaScript are not only a language function similar to methods in Java, but can also exist as objects. This article will discuss some special usage of functions in JavaScript, including the call, apply, and bind prototype methods.
I. Function Basics
Functions in JavaScript are language functions similar to methods in Java, but they can be defined independently of classes.

Function programming: Because JavaScript supports anonymous functions, functions can be used as objects. Therefore, JavaScript not only supports procedural programming (Object-Oriented is also a kind of procedural programming ), function programming is also supported.

Each call to a function has a special value -- context of this call -- the value of this keyword. If a function is attached to an object as an attribute of the object, it is called the object method. When a function is called through this object, this object is the context of the call, that is, the value of this of the function.

Note that this is a keyword, not a variable or attribute name. JavaScript syntax does not allow this assignment.

A function is an object.

The biggest difference between functions in JavaScript and methods in Java or functions in C is that functions in JavaScript are also an object. But this does not mean that all objects are functions. A function is a special object that contains executable code and can be called by other code.

Unlike variables, this keyword has no scope restriction. nested functions do not inherit this from the functions that call it. -If a nested function is called as a method, the value of this points to the object that calls it. -If a nested function is called as a function, the value of this is not a global object (in non-strict mode) or undefined (in strict mode ).

Many people mistakenly think that this will point to the context of the I outer function when calling the nested function. If you want to access the this value of this external function, you need to save the value of this in a variable, which 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. The value of this is a global object or undefined console. log (self = o); // true }}}


JavaScript functions can be nested in other functions so that they can access any variables in the scope of their definitions. This means that JavaScript functions constitute a closure (closure), which brings very powerful programming capabilities to JavaScript.

Function as Value
In JavaScript, a function is not only a syntax but also a value. That is to say, you can assign a function to a variable and store it in the attributes of an object or an array element, input another function as a parameter.

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

Function. prototype. call ()AndFunction. prototype. apply ()

Call () and apply () can be seen as the method of an object. They call functions indirectly by calling methods. Their first parameter is the parent object of the function to be called. It is the call context and can be referenced by this in the function body. The apply () method and the call () method have the same effect, but the function transmission method is different. Their real parameters are put in an array.

For example, the function f () is called in the form of an object o, and two parameters are passed in. You can use this code:

Var o ={}; function f (a, B) {return a + B;} f. call (o, 1, 2); // using function f as the o method is actually re-configuring the context f of function f. apply (o, [1, 2]);

For another example, use the call method to call an anonymous function:

In the for loop in the following example, an anonymous function is created, and each array element is executed as the specified this value by calling the call method of the function. The main purpose of this anonymous function is to add a print method to each array element object. This print method can print the correct index number of each element in the array. Of course, it is not necessary to pass the array element as the this value into the anonymous function (normal parameters are acceptable) to demonstrate the call usage.

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.print(); }).call(animals[i], i);}

Function. prototype. bind ()

Bind () is a new method added in ES5. It can be seen from the name that the main function of this method is to bind the function to an object. When the bind () method is called on function f () and an object o is input as a parameter, this method returns a new function: (called as a function) calling a new function will call the original function f () as the o method. For example:

Function f (y) {return this. x + y;} var o = {x: 1}; var g = f. bind (o); // call g (x) To call o. f (x) g (2); // 3

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

// Return a function. Call it to call method f () in o and pass all its real parameters function bind (f, o) {if (f. bind) return f. bind (o); // If the bind () method exists, use the bind () method else return function () {return f. apply (o, arguments );}}

Ii. Functional Programming
JavaScript is not a functional programming language, but it can manipulate a function like an object, that is, it can be applied to JavaScript.

Use functions to process Arrays

Suppose there is an array where all array elements are numbers. We want to calculate the average and standard deviation of these 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 = => x - mean);

Var stddev = Math. sqrt (deviations. map (square). reduce (sum)/(data. length-1 ));
High-order functions

A high-order function is a function used to operate functions. It receives one or more functions as parameters and returns a new function. For example:

Function not (f) {return function () {var result = f. apply (this, arguments); return! Result ;};}// the var even = function (x) {return x % 2 === 0 ;}; var odd = not (even); // a new function that does the opposite of even () [1, 1, 3, 5, 5]. every (odd); // true, each function is an odd number

Function not () is a high-order function because it returns a new function. This new function passes its real parameters into f () and returns the logical non-return value of f.

The above describes the usage of call (), apply (), and bind () in javascript. I hope this will be helpful for your learning.

Articles you may be interested in:
  • Discussing Function. apply () II ------ using Apply parameter array to improve JavaScript Program Performance
  • JS object-oriented, prototype, call (), apply ()
  • Introduction to the use of the apply () and call () methods in JavaScript
  • How to call () and apply () based on the Inheritance Mechanism in JavaScript
  • Introduction to prototype. bind () in JavaScript
  • $ Apply () method in angularJS
  • The magic call () method in JavaScript
  • Analysis of the apply () method in Javascript

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