Play with methods :call and apply
- 2020-03-30 02:52:49
- OfStack
In ECMAScript v3, these two methods are defined for the Function stereotype, and they both work the same way: you can call a Function just like you would any other object method.
The following is easy to understand, first look at the code:
function Introduce(name,age)
{
document.write("My name is "+name+".I am "+age);
}
var p=new People();
Introduce.call(p,"Windking",20);
As for the above code, Introduce is the method of p after the use of call. Do you understand? Using the call method, the above code is equivalent to this code:
function People(name,age)
{
this.name=name;
this.age=age;
this.Introduce=function(){
document.write("My name is "+name+".I am "+age);
};
}
1. Share methods. First look at the code:
function Introduce(name,age)
{
document.write("My name is "+name+".I am "+age);
}
This is a method of self-introduction. Now suppose we have a boy's class and a girl's class (I'm just going to demonstrate here, in practice, using a parent class of People), because their Introduce is the same, so we can share this method.
function Boy()
{
this.BoyIntroduce=function(){
Introduce.call(this,name,age);
};
}
The same goes for Girl, so we can avoid writing code. Actually, this is a little far-fetched, because we could have written it as:
function Boy()
{
this.BoyIntroduce=function(){
Introduce(name,age);
}
}
But this time, if we use Apply, it will look a lot easier:
function Boy()
{
this.BoyIntroduce=function(){
Introduce.apply(this,arguments);
};
}
Is it a lot easier? If the parameter is a lot of words, so is it not necessary to write so a dense string of parameters it!
2. Cross-domain invocation
See a simple example (for demonstration purposes only, no value whatsoever) :
function Boy(name,age)
{
this.BoyIntroduce=function(){
document.write("My name is "+name+".I am "+age);
}
}
function Girl(name,age)
{
}
This is a Boy and a Girl class, and then we write the following code:
Var b = new Boy (" Windking ", 20);
B.B oyIntroduce ();
Var g = new Girl (" Xuan ", 22);
Introduce the call (g, "Xuan", 22).
3. True use -- inheritance
All right, that's a lot of little tricks, but here's the most common use of call and apply, which is to construct inheritance.