標籤:建立 function eal llb 接受 方便 構造 lan nim
參考了這篇文章:http://www.tuicool.com/articles/EVF3Eb
給幾個例子
function add(a,b) { alert(a+b); } function sub(a,b) { alert(a-b); } add.call(sub,3,1);
這個運行是什麼呢?答案:
4. 啟動並執行是add.因為call是啟動並執行調用者。將第一個參數作為this參數來使用。
再來一個例子
function Animal(){ this.name = "Animal"; this.showName = function(){ console.log(this.name); } } function Cat(){ this.name = "Cat"; } var animal = new Animal(); var cat = new Cat();animal.showName.call(cat,","); 或者animal.showName.apply(cat,[]);
答案是:
Cat。 因為this換做了Cat。
另外,繼承時候用來調用父類的建構函式:
function Animal(name){ this.name = name; this.showName = function(){ console.log(this.name); } } function Cat(name){ Animal.call(this, name); } var cat = new Cat("Black Cat"); cat.showName();
調用完父類之後,cat也有了showName的方法。
下面這兩種調用基本等價:
myfunc.call(func,"var"," fun");myfunc.apply(func,["var"," fun"]);
而關於bind:作用:改變了內容相關的this
bind與call不同點有兩個:
①bind的傳回值是函數。
//使用bind是 返回改變上下文this後的函數
//使用call是 改變上下文this並執行函數
②後面的參數的使用也有區別
function f(a,b,c){ console.log(a,b,c);}var f_Extend = f.bind(null,"extend_A")f("A","B","C") //這裡會輸出--> A B Cf_Extend("A","B","C") //這裡會輸出--> extend_A A Bf_Extend("B","C") //這裡會輸出--> extend_A B Cf.call(null,"extend_A") //這裡會輸出--> extend_A undefined undefinedcall 是 把第二個及以後的參數作為f方法的實參傳進去而bind 雖說也是擷取第二個及以後的參數用於之後方法的執行,但是f_Extend中傳入的實參則是在bind中傳入參數的基礎上往後排的。
所以,以下兩個是等價的:
var f_Extend = f.bind(null,"extend_A")//↓↓↓var f_Extend = function(b,c){ return f.call(null,"extend_A",b,c);}
有一個應用情境:
例如現在有一個方法 根據不同的檔案類型進行相應的處理,通過bind 就可以建立出簡化版的處理方法function FileDealFunc(type,url,callback){ if(type=="txt"){...} else if(type=="xml"){...} .....}var TxtDealFunc = FileDealFunc.bind(this,"txt");//這樣使用的時候更方便一些FileDealFunc("txt",XXURL,func); //原來TxtDealFunc(XXURL,func); //現在
對於舊的版本,可以用以下方式做相容處理(EcmaScript5中擴充了叫bind的方法(IE6,7,8不支援))
if (!Function.prototype.bind) { Function.prototype.bind = function(obj) { var _self = this ,args = arguments; return function() { _self.apply(obj, Array.prototype.slice.call(args, 1)); } }}
不過上面的函數,好像只接受了一個參數。
JS裡面的call, apply以及bind