Measure the test taker's understanding about Function. prototype. bind in javascript.

Source: Internet
Author: User
This article mainly introduces how to understand Function. prototype. bind in javascript. It has some reference value. If you are interested, please take a look. When we are new to Javascript, we may not need to worry about function binding, but when we need to keep the context object this in another function, we will encounter corresponding problems, I have seen many people assign this value to a variable (such as self, _ this, And that), especially var that = this is the most common problem I have seen, in this way, you can use it after changing the environment. These are all possible, but there is also a better and more proprietary method, that is, using Function. prototype. bind, which will be explained in detail below.

Part 1: Problems to be Solved

First, let's look at the following code:

var myObj = {   specialFunction: function () {   },   anotherSpecialFunction: function () {   },   getAsyncData: function (cb) {    cb();  },   render: function () {this.getAsyncData(function () {      this.specialFunction();      this.anotherSpecialFunction();    });  }}; myObj.render();

Here I want to create an object that contains the first two common methods. The third method can pass a function and the passed function is executed immediately; the last method will call the getAsyncData method of the myObj object. this is used here, and a function is introduced in the getAsyncData method. this function continues to call the first two methods of this object, when this is still used, many people can see the problem. Enter the above Code in the console and get the following results:

TypeError: this.specialFunction is not a function

Part 2: Problem Analysis

In the render method of the object, this does point to the myObj object, so we can use this. getAsyncData calls the function in this object, but when we pass the function as a parameter, this points to the global environment window, because there are no first two methods in the object in the global environment, an error is reported.

Part 3: several ways to solve the problem

So what we need to do is to correctly call the first two methods in the object. Many people use this method to obtain this in the object environment and assign it to another variable, this can be called in the subsequent environment, as shown below:

render: function () {  var that = this;  this.getAsyncData(function () {    that.specialFunction();    that.anotherSpecialFunction();  });}

Although this method is feasible, using Function. prototype. bind () makes the code clearer and easier to understand, as shown below:

render: function () {   this.getAsyncData(function () {     this.specialFunction();     this.anotherSpecialFunction();   }.bind(this)); }

Here we successfully bound this to the environment.

Here is another simple example:

var foo = {  x: 3} var bar = function(){  console.log(this.x);} bar(); // undefined var boundFunc = bar.bind(foo); boundFunc(); // 3

The following example is also common:

this.x = 9;  // this refers to global "window" object here in the browservar module = { x: 81, getX: function() { return this.x; }}; module.getX(); // 81 var retrieveX = module.getX;retrieveX(); // returns 9 - The function gets invoked at the global scope // Create a new function with 'this' bound to module// New programmers might confuse the// global var x with module's property xvar boundGetX = retrieveX.bind(module);boundGetX(); // 81

Part 4: browser support

However, this method is not supported in IE8 and below, so we can use the method provided by MDN to make IE support the. bind () method in earlier versions:

if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) {  if (typeof this !== "function") {   // closest thing possible to the ECMAScript 5 internal IsCallable 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,                aArgs.concat(Array.prototype.slice.call(arguments)));    };   fNOP.prototype = this.prototype;  fBound.prototype = new fNOP();   return fBound; };}

The above is all of the content in this article. I hope it will be helpful for everyone's learning and support for PHP's Chinese Web.

For more information about Function. prototype. bind methods in javascript, refer to PHP!

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.