call()方法功能:指定函數的this,執行函數並傳參javascript
參數:java
fn.call(thisArg,arg1,arg2,ar3,......)數組
thisArg 指定讓this指向的對象,若指定了null或者undefined則內部this指向windowapp
arg1,arg2,ar3,......參數列表函數
返回值是函數本身的返回值
this
與apply()方法相似,只有一個區別,就是call()方法接受的是若干個參數的列表,而apply()方法接受的是一個包含多個參數的數組。prototype
應用:借用對象沒有的方法3d
更適用於將類數組對象用數組方法操做一些code
// call // 類數組對象 ,它就沒有數組Array的原型對象prototype上的方法,好比push、splice等 var o = { 0:11, 1:22, 2:33, 3:44, length:4 }; console.log(o); //當增長一項數據時 o["4"] = 55; o.length = 5; console.log(o);//須要將類數組對象中的length手動加 1 //call()方法,能夠改變this的指向 Array.prototype.push.call(o,99); console.log(o); console.log(o.length); console.log(o[5]);
apply()方法功能:指定函數的this,執行函數並傳參對象
參數:fn.apply(thisArg,[arsArray])
第一個參數是指定讓this指向的對象,第二個參數是以一個數組(或相似數組的對象)形式提供的參數。
應用:能夠指定函數的this,而且經過數組方式進行傳參
適用於將數組打散進行操做
//apply 打散數組 var arr = [2,3,8,90,1]; console.log(1,2,3); console.log.apply(console,arr);
打散數組成散列式的
可讓數組使用Math的max方法
var arr = [2,3,8,90,1]; // 內置Js中的一些方法方法 console.log(Math.max(1,78,2,3)); //利用apply方法,將數組傳給max的第二個參數 console.log(Math.max.apply(Math,arr)); //第一個參數this指向,仍是指向Math自己,這裏能夠寫Math,能夠寫null
bind()方法功能:指定函數的this,不能執行函數但能夠傳參
參數:fn.bind(thisArg,arg1,arg2,ar3,......)
第一個參數是 指定讓this指向的對象,第二個參數及之後,是函數參數的列表
返回值:返回一個新的指定了this的函數(即綁定函數)
應用:指定this,不須要當即執行函數的狀況
適用於事件函數(定時器、延時器)
//bind //修改定時器的函數內部的this var o = { name:"lili", age:12, years:function(){ setInterval(function(){ console.log(this.age);//定時器中的this指向的是window對象 // 而window對象沒有age,因此輸出錯誤 },1000) } }; o.years();// window對象沒有age,輸出undefined
更改定時器中的this:
years:function(){ setInterval(function(){ console.log(this.age);//定時器中的this指向的是window對象 // 而window對象沒有age,因此輸出錯誤 }.bind(this),1000)//更改this指向o }
更改事件函數中的this:
//bind //修改定時器的函數內部的this var o = { name:"lili", age:12, years:function(){ setInterval(function(){ console.log(this.age);//定時器中的this指向的是window對象 // 而window對象沒有age,因此輸出錯誤 }.bind(this), 1000)//更改this指向 } }; o.years();// window對象沒有age,輸出undefined // 更改定時器中的this //更改 事件函數中的this指向 document.onclick = function(){ console.log(this); };
document的this指向
更改document中的this指向o:
document.onclick = function () { console.log(this); }.bind(o);//指向o
call 和 apply特性同樣