Home > Article > Web Front-end > Summary of usage of call and apply in js_javascript skills
I went for an interview the day before yesterday, and a gg asked about some js knowledge. There was a question about the usage of call and apply. Although I used the call method 365 days ago, I still couldn’t answer it at that time. I will summarize it in depth today
call and apply, their function is to bind the function to another object to run
Format and parameter definitions of both:
call( thisArg [, arg1, arg2,...] ); // Parameter list, arg1, arg2,...
apply(thisArg [, argArray] ); // Parameter array, argArray
The this pointer inside the above two functions will be assigned thisArg, which can realize the purpose of running the function as a method of another object
1. Simple usage of call
First, let’s look at a simple example (call):
Then, the running results are as follows:
global varTest environment: Google Chrome 10.0.648.45
Finally, the analysis results
1. The global object window calls the function gFunc. this points to the window object , so this.value is global var
2. The function gFunc calls the call method. this points to the first parameter window object by default, so this.value is also global var
3. The function gFunc calls the call method. this points to the first parameter new mFunc() by default, which is the object of mFunc , so this.value is the member variable of mFunc member var
4. The function gFunc calls the call method. this points to the first parameter input text control by default, that is, the control with id='idTxt', so this.value is the value of the input control input text
5. Function func2 calls the call method. this points to the first parameter func function object by default, so this.value is this.a, that is, func
6. Function func2 calls the call method. The second parameter belongs to the parameter of the function object func2, so alert(x) is the second parameter func2
2. Call inheritance usage and improvements
js uses call to simulate inheritance
Test code:
baseB member
baseB member
测试环境:Google Chrome 10.0.648.45
结果分析:
预期的结果,应该是输出 baseA member 和 baseB member,但实际输出却是 baseB member 和 baseB member
(已在IE9、8、6,Maxthon、Chrome、FF、Opera、Safari、360等浏览器测试过,结果都是后者:baseB member)
至此,机器是不会错的,这就需要我们深入分析
我们可能会很容易想到是this引起的,this两次都指向了baseB对象,但是推测真是这样吗?
为了探究实质,我们借助chrome浏览器的调试工具,下断点,进行调试,结果发现:
当调用extend.showSelfA();时,此时的this指向extendAB(并不是我们推测的两次都指向baseB对象)
真实原因是extendAB对象的成员变量member在被baseB.call(this);实例化时,被baseB的成员member覆盖了,即extendAB的成员member由baseA member赋值成了baseB member
当然,我们也可以对上面baseA代码稍作修改,来验证我们调试分析的正确性:
baseA member
baseB member
结果和我们的预期相同,同时chrome调试信息也验证了我们的正确性:
继承改进(prototype)
以上模拟继承方法,仔细分析不是最好的。
因为每次在函数(类)中定义了成员方法,都会导致实例有副本,因此可以借助prototype原型,进行改进
改进举例如下: