On the usage of javascript call of apply of bind of

  • 2020-12-26 05:34:02
  • OfStack

A function in JavaScript is not only a language function similar to the methods in Java, it can also exist as an object. This article will explore one of the special uses of JavaScript functions, including call, apply, and bind3 prototype methods.
1. Function basis
The function in JavaScript is a language function similar to the method in Java, but it can be defined independently of the class.

Functional programming: Since JavaScript supports anonymous functions, it is possible to use functions as objects, so JavaScript supports not only procedural programming (object-oriented is also a type of procedural programming), but also functional programming.
context

Each call to the function has a special value -- the context of the call (context) -- that is the value of the this keyword. If a function is mounted on an object as a property of the object, it is called the object's method. When a function is called through this object, the object is the context of the call, which is the this value of the function.

Note that this is a keyword, not a variable or an attribute name. The syntax for JavaScript does not allow assigning values to this.

A function is an object

The biggest difference between a function in JavaScript and a method in Java or a function in C 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 variables, the keyword this has no scope limit, and nested functions do not inherit this from the functions that call it. - If a nested function is called as a method, its this value points to the object calling it. - If a nested function is called as a function, the value of its this is either a global object (in non-strict mode) or undefined (in strict mode).

Many people make the mistake of thinking that this refers to the context in which i uses its outer functions when calling nested functions. If you want to access the value of this for this external function, you need to store the value of this in a variable with the same scope as the internal function. Such as:


var o = {
 m: function() {
  var self = this;
  console.log(this==o); // true
  f();
  
  function f() {
   console.log(this === o); // false . this Is a global object or undefined
   console.log(self === o); // true
  }
 }
}

closure

JavaScript's functions can be nested within other functions so that they have access to any variable in the scope in which they were defined. This means that the JavaScript function constitutes a closure (closure), which gives JavaScript very strong programming power.

As a function of values
In JavaScript, a function is not only a syntax, but also a value, that is, you can assign a function to a variable, store it in an attribute of an object or an element of an array, pass in another function as an argument, and so on.

bind, call, apply
Each function contains an 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 properties from the prototype object.

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

call() and apply() can look at methods as objects that call functions indirectly by calling methods. Their first argument is the parent object to call the function, which is the calling context and is referenced within the function body via this. The apply() method does the same thing as the call() method, except that the function is passed in a different way and its arguments are put into an array.

For example, call the function f() in the form of an object o and pass in two arguments. You can use code like this:


var o = {};

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

f.call(o, 1, 2);    //  The function f As a o The method, in effect, resets the function f The context in which the 
f.apply(o, [1, 2]);

Here's another example of calling an anonymous function using the call method:

In the for loop in the example below, we create an anonymous function and then execute that 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 one print method to each array element object, which prints out the correct index number of each element in the array. Of course, you don't have to pass in the array element as the this value to the anonymous function (ordinary arguments will do), just 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. As the name suggests, the main purpose of this method is to bind functions to an object. When the bind() method is called on the function f() and an object o is added as an argument, this method returns a new function: (as a function call) calling the new function will call the original function f() as a method of o. Such as:


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

var o = {
 x: 1
};

var g = f.bind(o); //  By calling the  g(x)  To invoke the  o.f(x)
g(2); // 3

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


//  return 1 A function called by calling it o The methods in f() , passing all its arguments 
function bind(f, o) {
 if (f.bind) return f.bind(o); //  if bind() Method exists, use bind() methods 
 else return function () {
  return f.apply(o, arguments);
 }
}

2. Functional programming
JavaScript is not a functional programming language, but in JavaScript you can manipulate functions like object 1, which means you can apply functional programming techniques to JavaScript.

Use functions to handle arrays

Let's say I have an array of numbers, and I want to calculate the mean and the 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 = 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 operates on a function, takes one or more functions as arguments, and returns a new function. Here's an example:


function not(f) {
 return function () {
  var result = f.apply(this, arguments);
  return !result;
 };
}

//  judge x If it's an even function 
var even = function(x) {
 return x % 2 === 0;
};

var odd = not(even);      // 1 The new function, the things that it does and even() On the contrary 
[1, 1, 3, 5, 5].every(odd);   // true Every 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-return value of f.

javascript (), apply(), bind(), javascript (), bind(), javascript ().


Related articles: