Some jquery plug-ins often see a similar callback.call (xxx,xxx) while seeing that the book says call and apply functions can change scopes, it's not quite clear how changing scopes is primarily about solving problems, having alternatives, or These 2 functions mainly to solve what problems, application scenarios, when to use the most appropriate, each read this code dizzy, and suddenly jumped out of the linear reading, feeling a bit around
Call and apply the role is very simple, is to change the context, the application of the scene is too much, although sometimes just for "beautiful", the following several are my common.
1.
Copy Code code as follows:
Object.prototype.toString.call (OBJ)
Used to determine the type of OBJ
Arguments is similar to array, but he does not have an array of push and so on, how to do?
Array.prototype.push.call (arguments)
3.Javascript does not have the concept of a private method, want to use closure to implement
(function () {
var person = function () {
this.dosomething = function () {
_privatefunction.call (this);
}
}
var _privatefunction = function () {
}
window. person = person;
}). Call (window);
That's pretty much what it means, callback, when you want the context in your callback to be the current context, what's the benefit of call or apply?
This time in your callback this is referring to the current context. For example, a class person, and then his method say has a callback argument, and if the callback is performed by ordinary parentheses, then other methods of executing person in this callback need to be implemented with Person.other. But after switching the context, it is this.other to fix the code comparison as follows:
var person = function () {
};
Person.prototype.say = function (callback) {
callback ();
};
Person.prototype.other = function () {
};
var vincent = new Person ();
Vincent.say (function () {
vincent.other ();
});
The call was used:
var person = function () {
};
Person.prototype.say = function (callback) {
callback.call (this);
Person.prototype.other = function () {
};
var vincent = new Person ();
Vincent.say (function () {
this.other ();
});
The above mentioned is the entire content of this article, I hope you can enjoy.