Home  >  Article  >  Web Front-end  >  A brief analysis of the use and implementation of the bind() method in Javascript_javascript skills

A brief analysis of the use and implementation of the bind() method in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:02:531262browse

Before discussing the bind() method, let’s look at a question:

var altwrite = document.write;
altwrite("hello");
//1. What’s wrong with the above code
//2. What is the correct operation
//3.How to implement the bind() method

For the above question, the answer is not too difficult. The main test point is the problem pointed by this. The altwrite() function changes the point of this to the global or window object, resulting in an illegal call exception during execution. The correct solution is to use bind () method:

altwrite.bind(document)("hello")
Of course, you can also use the call() method:

altwrite.call(document, "hello")
The focus of this article is to discuss the third issue, the implementation of the bind() method. Before starting to discuss the implementation of bind(), let’s first take a look at the use of the bind() method:

Binding function
The simplest use of bind() is to create a function so that the function has the same this value no matter how it is called. A common mistake is like the example above, taking the method out of the object and then calling it, hoping that this will point to the original object. If no special processing is done, the original object will generally be lost. Using the bind() method can solve this problem beautifully:

this.num = 9; 
var mymodule = { 
 num: 81,
 getNum: function() { return this.num; }
};

module.getNum(); // 81

var getNum = module.getNum; 
getNum(); // 9, 因为在这个例子中,"this"指向全局对象

// 创建一个'this'绑定到module的函数
var boundGetNum = getNum.bind(module); 
boundGetNum(); // 81 

Partial Functions

Partial Functions are also called Partial Applications. Here is a definition of partial functions:

Partial application can be described as taking a function that accepts some number of arguments, binding values ​​to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.

This is a very good feature. Using bind() we set the predefined parameters of the function, and then pass in other parameters when calling:

function list() { 
 return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// 预定义参数37
var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37] 
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3] 

Use together with setTimeout

Generally, this of setTimeout() points to the window or global object. When you need this to point to a class instance when using a class method, you can use bind() to bind this to the callback function to manage the instance.

function Bloomer() { 
 this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// 1秒后调用declare函数
Bloomer.prototype.bloom = function() { 
 window.setTimeout(this.declare.bind(this), 1000);
};

Bloomer.prototype.declare = function() { 
 console.log('我有 ' + this.petalCount + ' 朵花瓣!');
};

Note: The above method can also be used for event handling functions and setInterval methods

Bind function as constructor

Bound functions are also suitable for using the new operator to construct instances of the target function. When using a bound function to construct an instance, note: this will be ignored, but the parameters passed in will still be available.

function Point(x, y) { 
 this.x = x;
 this.y = y;
}

Point.prototype.toString = function() { 
 return this.x + ',' + this.y; 
};

var p = new Point(1, 2); 
p.toString(); // '1,2'


var emptyObj = {}; 
var YAxisPoint = Point.bind(emptyObj, 0/*x*/); 
// 实现中的例子不支持,
// 原生bind支持:
var YAxisPoint = Point.bind(null, 0/*x*/);

var axisPoint = new YAxisPoint(5); 
axisPoint.toString(); // '0,5'

axisPoint instanceof Point; // true 
axisPoint instanceof YAxisPoint; // true 
new Point(17, 42) instanceof YAxisPoint; // true 

In the above example, Point and YAxisPoint share prototypes, so it is true when using the instanceof operator.

Shortcut

bind() can also create shortcuts for functions that require a specific this value.

For example, if you want to convert an array-like object into a real array, the possible examples are as follows:

var slice = Array.prototype.slice;

// ...

slice.call(arguments); 

If you use bind(), the situation becomes simpler:

var unboundSlice = Array.prototype.slice; 
var slice = Function.prototype.call.bind(unboundSlice);

// ...

slice(arguments); 

Achievement

It can be seen from the above sections that bind() has many usage scenarios, but the bind() function was only added in the fifth edition of ECMA-262; it may not run on all browsers. This requires us to implement the bind() function ourselves.

First we can simply implement the bind() method by specifying a scope for the target function:

Function.prototype.bind = function(context){ 
 self = this; //保存this,即调用bind方法的目标函数
 return function(){
   return self.apply(context,arguments);
 };
};

Taking into account function currying, we can build a more robust bind():

Function.prototype.bind = function(context){ 
 var args = Array.prototype.slice.call(arguments, 1),
 self = this;
 return function(){
   var innerArgs = Array.prototype.slice.call(arguments);
   var finalArgs = args.concat(innerArgs);
   return self.apply(context,finalArgs);
 };
};

This time the bind() method can bind objects and also supports passing parameters during binding.

Continue, Javascript functions can also be used as constructors, so when the bound function is called in this way, the situation is more subtle, and the transfer of the prototype chain needs to be involved:

Function.prototype.bind = function(context){ 
 var args = Array.prototype.slice(arguments, 1),
 F = function(){},
 self = this,
 bound = function(){
   var innerArgs = Array.prototype.slice.call(arguments);
   var finalArgs = args.concat(innerArgs);
   return self.apply((this instanceof F ? this : context), finalArgs);
 };

 F.prototype = self.prototype;
 bound.prototype = new F();
 return bound;
};

This is the implementation of bind() in the book "JavaScript Web Application": by setting up a transit constructor F, the bound function and the function that calls bind() are on the same prototype chain, and the new operation is used operator calls the bound function, and the returned object can also use instanceof normally, so this is the most rigorous implementation of bind().

In order to support the bind() function in the browser, you only need to slightly modify the above function:

Function.prototype.bind = function (oThis) { 
  if (typeof this !== "function") {
   throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  }

  var aArgs = Array.prototype.slice.call(arguments, 1), 
    fToBind = this, 
    fNOP = function () {},
    fBound = function () {
     return fToBind.apply(
       this instanceof fNOP && oThis ? this : oThis || window,
       aArgs.concat(Array.prototype.slice.call(arguments))
     );
    };

  fNOP.prototype = this.prototype;
  fBound.prototype = new fNOP();

  return fBound;
 };

The above brief analysis of the use and implementation of the bind() method in Javascript is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn