一个apply的实例
看apply函數(shù)的理論知識的時候覺得很簡單,但后來看到書上一段小代碼,發(fā)現(xiàn)之前并沒有深刻地理解這個函數(shù),這里記下來做個筆記.
代碼如下:
function r(x){
return x;
}
function f(x){
x[0] =x[0]+">";
return x;
}
function o(){
var temp = r;
r = function(){
return temp.apply(this,f(arguments));
}
}
function a(){
o();
document.write(r("="));
}
?
?for (var i = 0; i <10; i++) {
?a();
?document.write("</br>")
?}
?
運行結果如下:
?
一開始沒有想明白為什么是先打印=再打印>,后來對代碼進行斷點處理之后,才發(fā)現(xiàn)其中的奧妙.
function r(x){
document.write("6");
return x;
}
function f(x){
x[0] =x[0]+">";
document.write("5");
for (var i = 0; i < arguments.length; i++) {
document.write(x[i]);
};
return x;
}
function o(){
var temp = r;
document.write("1");
r = function(){
document.write("4");
return temp.apply(this,f(arguments));
}
document.write("2");
}
function a(){
//document.write(r("="));
o();
document.write("3");
document.write(r("="));
}
a();
document.write("<br><br>");
// for (var i = 0; i <10; i++) {
// a();
// document.write("</br>")
// }
?
?
按照上文的提示,代碼運行順序是這樣的:
運行o()?
將r函數(shù)賦值給temp;
打印1;
重寫r函數(shù),不執(zhí)行;
打印2;
回到a函數(shù),打印3;
執(zhí)行r("=")函數(shù);
r函數(shù)在o()中被改寫,打印4;
返回一個temp函數(shù)
返回值中.先執(zhí)行f(arguments),
打印5
由于此時的arguments為"=",故f("=")的執(zhí)行結果為返回 =>
執(zhí)行函數(shù) temp(this,"=>")
打印6
返回?=>
所以最后的結果為123456=>
?
注意:
temp = r 是對函數(shù)的一個賦值;
r = function(){...} 只是寫了一個函數(shù)并沒有調(diào)用他,故此時不執(zhí)行該函數(shù);
apply函數(shù)中若第一個參數(shù)為this,即為調(diào)用他的函數(shù),若為其他對象或函數(shù),則執(zhí)行對象為第一個參數(shù)所設置的對象,第二個參數(shù)是一個arguments數(shù)組,若為函數(shù),則arguments是函數(shù)的返回值.
轉載于:https://www.cnblogs.com/julyys/p/4483685.html
總結
以上是生活随笔為你收集整理的一个apply的实例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [UiAutomator] UiSele
- 下一篇: myeclipse9 maven web