In the past, you might have directly set up self=this or That=this and so on, which would certainly work, but using Function.prototype.bind () would be better and look more professional.
Here's a simple example:
Copy Code code as follows:
var myobj = {
Specialfunction:function () {
},
Anotherspecialfunction:function () {
},
Getasyncdata:function (CB) {
CB ();
},
Render:function () {
var that = this;
This.getasyncdata (function () {
That.specialfunction ();
That.anotherspecialfunction ();
});
}
};
Myobj.render ();
In this example, in order to maintain the myobj context, set a variable that=this, which is feasible, but does not use Function.prototype.bind () looked neater:
Copy Code code as follows:
Render:function () {
This.getasyncdata (function () {
This.specialfunction ();
This.anotherspecialfunction ();
}.bind (this));
}
When you call. Bind (), it simply creates a new function and then passes this to this function. The code to implement. Bind () is probably like this:
Copy Code code as follows:
Function.prototype.bind = function (scope) {
var fn = this;
return function () {
return fn.apply (scope);
};
}
Here's a simple example of using Function.prototype.bind ():
Copy Code code as follows:
var foo = {
X:3
};
var bar = function () {
Console.log (this.x);
};
Bar (); Undefined
var boundfunc = Bar.bind (foo);
Boundfunc (); 3
is not very easy to use it! Unfortunately, IE8 and the following IE browsers do not support Function.prototype.bind (). The supported browsers have Chrome 7+,firefox 4.0+,ie 9+,opera 11.60+,safari 5.1.4+. Although not supported by browsers such as IE 8/7/6, the Mozilla Development Group has written a function similar to the old version of IE, with the following code:
Copy Code code as follows:
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 being bound 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;
};
}