for the small partners who want to delve into JS, call and apply seem to be the foundation of the foundation, because what? If you've seen the JQ and there are some new frameworks, you'll find that their bottom-up encapsulation method is a variety of callbacks. The advantage is to save the developer to write a lot of code to encapsulate the method of time, let the developer remember the method of call, come up with can use , what Agular,vue ... In fact, they are all these things, after all, these frameworks do not create a new language, are based on the native JS to make, with JS to engage, then you have to abide by the original JS rules, then call and apply the two methods are to give the framework to play the imagination of the space ....
well said so much, the sermon is not much to say, directly on the code bar !
function aa () {
//(3) So, the this in AA, point to BB
Console.log (This)
This.say = function (n) {
console.log (n)//' I am xx '
}
}
function dd () {
Console.log (This)
this.age = function (n) {
console.log (n)//
}
}
//AA () is called here and is actually called in the window;
//Then this in AA points to window
//because: who called the function, the this of the function points to who.
//AA ();
function bb () {
//(1) Call AA here, you can think of the AA that was called in BB;
//(2) but in fact it is the scope of the BB, passed in the AA,
Aa.call (this);
Call an object, is simply the inheritance;
Call multiple objects, that is, multiple inheritance;
Dd.call (this);
}
var cc = new BB ();
Cc.say (' I am xx ')
Cc.age (22)
is a simple small example, there are several key points, one is the AA and DD These two functions are actually provided only two methods, then through new BB This function, then aa,dd the scope of the two functions passed to BB This function, the second is passed the value, Then CC can call the scope of the BB, then Cc.say (' I is xx ') passed through BB to the AA function say corresponding function, and called the Say function, similarly, DD is the same. Apply, like him, does not say much except that it is a passing array, not another type, when the value is passed.
So through the call method, you can imagine, if you want to make a function of the general method of encapsulation, then this is a good solution, you can define a lot of methods, and then remember the method name, when you want to use these methods, only need to put BB such function new, assign to a variable, The direct value is good, how simple, the code reusability to get the quality improvement!
A simple demo of call and apply in JS