settimeout Change this point

Source: Internet
Author: User

<! DOCTYPE html>

The setTimeout inside the above points to the window;

<! DOCTYPE html>

  

<! DOCTYPE html>
<! DOCTYPE html>
<! DOCTYPE html>

<! DOCTYPE html>

  

Bind, as the name implies.

The bind () method creates a new function, and when the new function is called, its this value is the first parameter passed to bind (), and its arguments are the other parameters of bind () and its original parameters.

The last sentence of the above definition is a bit around, let's take a look.

Bind () takes an infinite number of arguments, the first parameter is the this point of the new function it generates, for example, I pass a window, no matter where it is called, this new function points to the window, the new function parameter is the second, third, Fourth of bind () .... The nth parameter is added to its original argument. (All right, I've been blindfolded myself)

We still look at chestnuts better understand, give a bind () the most basic way to use:

This.x = 9; var module = {  x:81,  getx:function () {return this.x;}}; Module.getx (); Returns 81var Retrievex = Module.getx;retrievex (); Returns 9, in this case, "this" points to the global scope//creates a new function that binds "this" to the Module object///The Novice may be fooled by the global x variable and the attribute x in module = var boundgetx = Retrievex.bind (module); Boundgetx (); Returns 81

Here it is obvious that we are going to retrievex the window object, the result is definitely the X under window, we bind the module object to Retrievex's this, the problem is solved, no matter where it is called, this is the module object.

and other parameters of bind (), I believe that the first contact with BIND () friends see the above definition will be masked.

Or raise a chestnut:

Function List () {  return Array.prototype.slice.call (arguments);} var list1 = list (1, 2, 3); [1, 2, 3]//creates a function with a preset initial parameter var leadingthirtysevenlist = List.bind (Undefined,[69,37],{a:2}); var list2 = Leadingthirtysevenlist (); [[69,37],{a:2}]var list3 = Leadingthirtysevenlist (1, 2, 3); [[69,37],{a:2}, 1, 2, 3]

The list function is simple, insert each parameter into an array, we use BIND () to the list function to set the initial value, because do not change the list of this point, so the direct undefined, starting from the second argument, is to pass the value of the list function, The return values of List2 and list3 are a good indication of everything.

My own general use of the bind () scenario is with the settimeout function, because when you execute settimeout, this defaults to the Window object, which I did before using bind ():

    function coder (name) {        var = this;        That.name = name;        That.getname = function () {            console.log (that.name)        };        That.delaygetname = function () {            setTimeout (that.getname,1000)        };    }    var me = new Coder (' Jins ')    me.delaygetname ()//delay one second output Jins

A pointer to that cache this is defined in the top level of the function so that it is an instance of coder, regardless of how it is called, but it is always uncomfortable to define a variable.

Using bind () is a lot easier:

    function coder (name) {        this.name = name;        This.getname = function () {            console.log (this.name)        };        This.delaygetname = function () {            setTimeout (This.getName.bind (this), +)        };    }    var me = new Coder (' Jins ')    me.delaygetname ()//delay one second output Jins

This will be OK, directly to the settimeout this bound to the outer this, which is definitely what we want!

OK, let's talk so much, keep on learning!

bind()method creates a new function that becomes a binding function. When this binding function is called, the binding function takes the first parameter passed in when it is created this , and the second and later parameters of the incoming method, plus the arguments of the bind() binding function itself, are used as parameters of the original function in order to tune the original function.

In practical use we often encounter such problems:

var name =  "pig" ; function Person this.name = name; this.getname = function () {setTimeout (function () {Console.log (" hello,my name is "+this.name);} , 100); }}var Weiqi = new person ( "Guardian flag"); Weiqi.getname (); //hello,my name is pig           

This time the output is because the this this.name pig point is determined when the function is run, not when the function is defined, and because setTimeout it is only thought in the global context, this is the point window .

The previous approach to solving this problem is usually caching this , for example:

var name ="Pig";function person(name) { this.name = name; This.getname = function() { //) Here cache a This var self = this ; SetTimeout (function() { //Here is the self console.log with cache this ("hello,my name is" +self.name);},100);}} var Weiqi = New Person ("Guardian flag"); Weiqi.getname ();  Hello,my name is Wei Qi                

This solves the problem and is very convenient because it allows the settimeout function to access the context of the person.

Now there is a better solution, you can use the bind () function, the above example can be updated to:

var name = "pig"; function Person this.name = name; this.getname = function () {setTimeout (function () {Console.log (" hello,my name is "+this.name);}. Bind (this), 100); //notice the above line, add bind (this)}} var Weiqi = new person ( "Guardian flag"); Weiqi.getname (); //hello,my name is Wei Qi           

The simplest use of bind () is to create a function so that the function has the same this value regardless of the invocation. One of the most common mistakes JavaScript novices make is to take a method out of an object and then call it, hoping that this is the original object in the method (such as passing in the callback function). If you do not do special processing, you will generally lose the original object. Creating a binding function from the original function and the original object can be a pretty good solution to this problem:

Defining Global Variables Xvar x ="Window";Inmodule internal definition XVarmodule = {X:"Module",GetX:function () { console.log (this.x);}} Module.getx (); //Return module because getX ()var GetX = Module.getx;getx () is called inside the module;  Return to Window because this GetX () is called in the global scope //Bind GetX () and set the This value to modulevar boundgetx = Getx.bind (  module); Boundgetx (); //Return module, after binding this value is always module            

Browser support situation:

Support
Browser Version
Chrome 7
FireFox (Gecko) 4.0 (2)
Internet Explorer 9
Opera 11.60
Safari 5.14

Unfortunately, it is Function.prototype.bind not supported in IE8 and the following versions, so if there is no alternative, there may be a problem at run time. bindthe function was added to the fifth version of ECMA-262. It may not be able to run on all browsers. You can add the following code to the script section to make the feature available to unsupported browsers bind() .

if (!Function.prototype.bind) {Function.prototype.bind =function(Othis) {if (typeofThis!=="function") {Closest thing possible to the ECMAScript 5 internal iscallable functionThrowNewTypeError ("Function.prototype.bind-what is trying to being bound is not callable"); }var Aargs =Array.prototype.slice.call (arguments, 1), Ftobind = This , Fnop = function () {}, Fbound = func tion () { 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;};}                
Grammar

fun.bind(thisArg[, arg1[, arg2[, …]]])

Parameters

thisArg, when the binding function is called, the parameter is pointed to when the original function is run, and when the new binding function is called with the operator, the argument is not valid.

arg1, arg2, …, when the binding function is called, these parameters, together with the parameters of the binding function itself, are ordered as arguments to the original function when it is run.

Describe

The bind () function creates a new function (a bound function) with the same function body (built-in call property in the ECMAScript 5 specification), which cannot be overridden when the function (the original function of the binding function) is invoked when the this value is bound to the first parameter of bind (). When a binding function is called, bind () also accepts a preset argument to the original function. A binding function can also use the new operator to create an object: This behavior is like using the original function as a constructor. The provided this value is ignored, and the parameters that the colleague invokes are provided to the impersonation function.

Summarize:

<! DOCTYPE html>

  

settimeout Change this point

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.