1. 程式人生 > 其它 >this-> call,apply,bind

this-> call,apply,bind

<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <metahttp-equiv="X-UA-Compatible"content="IE=edge"> <metaname="viewport"content="width=device-width,initial-scale=1.0"> <title>Document</title> <style> *{ margin:0; padding:0; }
html,body{ height:100%; overflow:hidden; background:-webkit-linear-gradient(topleft,lightblue,lightpink); } </style> </head> <body> <script> /** *this的幾種情況 *+事件繫結 *+函式執行 *+自執行函式 *+回撥函式 *+... *+建構函式執行 *+基於call/apply/bind改變函式中的this *+箭頭函式中沒有自己的this,所用到的this是使用上下文中的 **/ //Function.prototype->call/apply/bind所有的函式都可以調取這三個方法

//window.name="WINDOW"; //letobj={ //name:"Eric", //age:29 //}
//functionfn(x,y){ //console.log(this.name,x+y); //}
//fn()//this->window"WINDOW"
//obj.fn();//obj.fnisnotafunction
//this->objEric //fn.call(obj)//(fn先基於__proto__找到Function.prototype.call, //把call方法執行的時候,call方法內部實現了一些功能,會把fn執行, //並且讓fn中的this變為第一個實參值)
//fn.call(obj,10,20)//this->objx->10y=20Eric30 //fn.call()//this->window嚴格模式下是undefined //fn.call(null)//this->window嚴格模式下是null //============================ //apply的作用和細節上和call一樣,只有一個區別,傳遞給函式實參的方式不一樣 //fn.apply(obj,[10,20])//最後結果和call是一樣的,只不過apply方法執行的時候要求:傳遞給函式的實參資訊 //都要放置在一個數組匯中,但是apply內部也會向call方法一樣,把這些實參資訊一項項的傳遞給函式
//需求1獲取陣列中的最大值 //letarr=[10,30,15,36,23]; //0 //letmax=Math.max(...arr) //console.log(max);
//1 //arr.sort((a,b)=>{ //returnb-a //}) //letmax=arr[0] //console.log(max);
//2 //varmax=arr[0] //for(vari=0;i<arr.length;i++){ //if(max<arr[i]){ //max=arr[i] //} //} //console.log(max);
//3 //letmax=arr.reduce((result,item)=>{ //returnitem>result?item:result //}) //console.log(max);



//================================ //functionsum(){ ///** //*arguments:實參集合,它是一個類陣列,不是Array的例項,所以不能呼叫Array.prototype //*上的方法,但是結構和陣列非常的相似,都是索引+length //* //**/ ////console.log(arguments);
////letarr=Array.from(arguments)//1 ////letarr=[...arguments]//2
////letarr=[] ////for(leti=0;i<arguments.length;i++){ ////arr.push(arguments[i]) ////}
//letarr=[].slice.call(arguments) //returnarr.reduce((result,item)=>{ //returnresult+item //}) //} //lettotal=sum(10,20,30,40,10) //console.log(total);

//======================================== //window.name="WINDOW"; //letobj={ //name:"Eric", //age:29 //}
//functionfn(x,y){ //console.log(this,x,y); //} /** *this->body *x=Event *yundefined */ //document.body.onclick=fn;
/** *this->window *x->undefined *y->undefined */ //setTimeout(fn,1000)

/** *call/apply在處理的時候,會立即執行 * */ //document.body.onclick=fn.call(obj,10,20) //setTimeout(fn.call(obj,10,20),1000) //預先處理思想 //document.body.onclick=function(ev){ //fn.call(obj,10,20) //}
//setTimeout(function(){ //fn.call(obj,10,20) //},1000)

//bind不會立即執行,只是處理了this和引數 //document.body.onclick=fn.bind(obj,10,20) //setTimeout(fn.bind(obj,10,20),1000)
//======================= //箭頭函式沒有自己的this letobj={ name:"Eric", age:29, fn:function(){ returnfunction(){ console.log(this); } } } letf=obj.fn(); f()//this->window
</script> </body> </html> 我是Eric,手機號是13522679763