search
HomeWeb Front-endJS TutorialA brief analysis of the use and implementation of the bind() method in Javascript_javascript skills

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),