函數四種調用模式以及其中的this指向
更新時間:2017年01月16日 16:18:30 作者:九成
本文主要介紹了函數四種調用模式以及其中的this指向的相關知識,具有一定的參考價值,下面跟著小編一起來看下吧
第一種:函數直接執(zhí)行模式
function add(a,b){ console.log(this); return a+b; } add(10,20)//this===window
第二種:對象方法的調用模式
var obj={ name:'aaa', age:20, said:function(){ console.log(this); } } obj.said();//this===obj,此處this指代被調用者
第三種:構造器的調用模式
function School(){ this.said=function(){ console.log(this); } } var nanj=new School(); nanj.said();//對象調用自己的方法,this===nanj,類似上面
第四種:call和apply調用模式
function change(a,b){ this.detial=a*b; console.log(this); } var p={}; change.call(p,4,5);//此處的this===p console.log(p.detial); var q=[]; change.call(q,5,10)//this===q console.log(q.detial); //apply和call一樣的用法,只不過apply第二個參數用數組進行傳遞 var arr=[]; change.apply(arr,[10,10]);//this===arr console.log(arr.detial); var str={}; change.apply(str,[20,20]);//this===str console.log(str.detial);
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關文章
javascript+jQuery實現360開機時間顯示效果
這篇文章主要介紹了javascript+jQuery實現360開機時間顯示效果,在文中給大家提到了js實現時間倒計時的代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-11-11