Recently with the JS class to write things, found an extremely painful thing, that is encapsulated in the class method of the this pointer will often change the point, lost context, resulting in a program error or crash.
Like what:
function Obj () {
This.type = "obj";
}
Obj.prototype = {
Show:function () {
Ettimeout (function () {
Console.log (This.type);
},300)
}
var obj = new obj ();
Obj.show (); undefined
Fortunately, the great JS has a number of ways to solve this problem. We can directly save a pointer to the context such as var self = this; Then use the cached self pointer, but JS contains Bind,apply,call and other useful methods to specify the context.
Syntax: Fn.bind (obj,arguments)
Fn.apply (obj,arguments)
Fn.call (obj,arguments)
Difference:
1.bind returns a method, while the remaining two calls the function directly;
2. The first parameter is the same, the context object is specified, the second parameter is an array, and the call corresponds to the shape
Reference: http://www.css119.com/archives/1376
Application of Bind,call,apply method in JS