理解 Prototype.js的bind()函數(shù)
fun.bind(this,arg1,arg2)
bind()方法會創(chuàng)建一個新的函數(shù)揩徊,稱為綁定函數(shù)张吉,fun方法在this環(huán)境下調用(這里的this可以綁定到任意對象)法挨,該方法可傳入連續(xù)多個參數(shù),第一個參數(shù)作為this,第二個及以后的參數(shù)則作為函數(shù)的參數(shù)調用
// The .bind method from Prototype.js
Function.prototype.bind = function() {
var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function() {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments));
)
}
}
一.Array.slice()和shift()和concat()
slice()有兩種看疗,一種是string.slice()诊胞,另外一種是Array.slice()暖夭。在數(shù)組Array中,slice()能夠基于當前數(shù)組中的一個或多個項創(chuàng)建一個新數(shù)組撵孤。它可以接受一個或兩個參數(shù)迈着,即要返回項的起始和結束位置。在只有一個參數(shù)的情況下邪码,slice()方法返回從該參數(shù)指定位置到當前數(shù)組末尾的所有項裕菠。如果有兩個參數(shù),該方法返回起始和位置結束位置之間的項闭专,但不包括結束位置的項, 且注意slice()方法不會影響原始數(shù)組
shift(): 刪除一個數(shù)組最前面的值奴潘,并且返回刪除值.
concat(): 可以基于當前數(shù)組中的所有項創(chuàng)建一個新數(shù)組。具體來說影钉,這個方法會先創(chuàng)建當前一個數(shù)組的副本画髓,然后接收到的參數(shù)添加到這個副本的末尾,最后返回新構建的數(shù)組平委。
var colors = ["red", "green", "blue", "yellow", "purple"];
var color1 = colors.concat("yellow",["black","brown"]);
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
alert(color1); //red,green,blue,yellow,purple,yellow,black,brown
alert(colors2); //green,blue,yellow,purple
alert(colors3); //green,blue,yellow
alert(colors); //red,green,blue,yellow,purple
二. call()和apply()
call()和apply()方法主要是用來擴充函數(shù)的作用域(把第一個參數(shù)作為自己的this)
call()和apply()方法接收兩個參數(shù):
apply(): 第一個參數(shù)是作用域奈虾,第二個是參數(shù)數(shù)組,其中第二個參數(shù)可以是數(shù)組實例廉赔,也可以是arguments對象肉微。
call(): 第一個參數(shù)依舊是作用域,然而傳參的方式不同昂勉,其參數(shù)必須逐個寫入
三. Array.prototype.slice.call(arguments)
arguments是一個關鍵字浪册,代表當前參數(shù),在Javascript中雖然arguments表面上以數(shù)組形式來表示岗照,但實際上沒有原生slice的功能村象,所以要使用call方法算是對arguments對象不完整數(shù)組功能的修正笆环。
Array.prototype.slice.call(arguments) === Array.prototype.slice.call(arguments,0)
Array.prototype.slice調用的是Array的原型方法,對于真正的數(shù)組是有slice()方法厚者,但是對于像arguments或者自己定義的一些類數(shù)組對象雖然存在length等若干屬性躁劣,但是并沒有slice()方法,所以對于這種類數(shù)組對象就得使用原型方法來使用slice()方法库菲,即Array.prototype.slice.(如果在自定義中的類數(shù)組對象中自定義了slice()方法账忘,就可以自然地直接調用了)。
因此熙宇,Array.prototype.slice.call(arguments,0)可以理解為:對于arguments類數(shù)組鳖擒,我們調用Array.prototype.slice原型方法,并用call()方法將作用域限定在arguments中烫止,此時:Array.prototype === arguments, 用參數(shù)0位slice()方法中地第一個參數(shù)蒋荚,即開始位置索引,_通過這種方法就將arguments類數(shù)組轉換位了真數(shù)組馆蠕。
var a = {
length: 2,
0: 'first',
1: 'second'
};
Array.prototype.slice.call(a); //["first","second"]
var a = {length: 2};
Array.prototype.slice.call(a); //["undefined","undefined"]