The front-end developer should be aware that the function functions object of the Javscript script can change the object that the internal scope (this) points to by using the call or Apply method to achieve more scalable functionality development. IE native support call and apply methods for function objects are supported in Firefox or other browsers, but the call and apply methods are immediately useful and executed, for example:
Copy Code code as follows:
var func = function () {
alert (this);
}.apply (window);
When the script parsing engine executes this code, it immediately pops up the dialog box and displays the object string. Our intention is to define the Func method acting on the Window object domain and then executing it later, but the call and apply methods do not satisfy our intent, and they are executed immediately.
After Google technical data, found that Firefox native support a bind method, this method is very good to meet our original intention, calling the method and call and apply, only after the definition is completed, the method will not execute when called later. But this bind method only has native support in the IE10 version of the browser, and a undefined error message will be given when executing below that version of the browser. So I had to surf the internet again Google Solutions, Kung Fu, we found a solution in the Firefox development station, that is, to increase the property prototype so that all browsers can support the Bind method, the code is as follows:
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;
};
}
Understand this piece of code need a little foundation, I just know how to use, if Daniel is interested in introducing the principle of the source code, thank you!
Simplicity is not an attitude, but a satisfaction.