在JavaScript中黍瞧,call尚困、apply和bind是Function對象自帶的三個方法掏膏,本文將通過幾個場景的應(yīng)用劳翰,來詳細理解三個方法。
- call()
call() 方法在使用一個指定的this值和若干個指定的參數(shù)值的前提下調(diào)用某個函數(shù)或方法馒疹。
當(dāng)調(diào)用一個函數(shù)時佳簸,可以賦值一個不同的 this 對象。this 引用當(dāng)前對象颖变,即 call 方法的第一個參數(shù)生均。
通過 call 方法,你可以在一個對象上借用另一個對象上的方法腥刹,比如Object.prototype.toString.call([])马胧,就是一個Array對象借用了Object對象上的方法。
語法 fun.call(thisArg[, arg1[, arg2[, ...]]])
thisArg
在fun函數(shù)運行時指定的this值衔峰。需要注意的是下面幾種情況:
(1)不傳佩脊,或者傳null蛙粘,undefined, 函數(shù)中的this指向window對象
(2)傳遞另一個函數(shù)的函數(shù)名威彰,函數(shù)中的this指向這個函數(shù)的引用出牧,并不一定是該函數(shù)執(zhí)行時真正的this值
(3)值為原始值(數(shù)字,字符串抱冷,布爾值)的this會指向該原始值的自動包裝對象崔列,如 String、Number旺遮、Boolean
(4)傳遞一個對象赵讯,函數(shù)中的this指向這個對象
1.1 例子
初級應(yīng)用例子
function a(){ //輸出函數(shù)a中的this對象 console.log(this); }
//定義函數(shù)b
function b(){} var obj = {name:'這是一個屌絲'}; //定義對象obj a.call(); //window a.call(null); //window a.call(undefined);//window a.call(1); //Number a.call(''); //String a.call(true); //Boolean a.call(b);// function b(){} a.call(obj); //Object
使用call方法調(diào)用匿名函數(shù)并且指定上下文的this
在下面的例子中,當(dāng)調(diào)用 greet 方法的時候耿眉,該方法的 this 值會綁定到 i對象边翼。
function greet() { var reply = [this.person, '是一個輕量的', this.role].join(' '); console.log(reply); }
var i = { person: 'JSLite.io', role: 'Javascript 庫。' };
greet.call(i);
// JSLite.io 是一個輕量的 Javascript 庫
使用call方法調(diào)用匿名函數(shù)
在下例中的for循環(huán)體內(nèi)鸣剪,我們創(chuàng)建了一個匿名函數(shù)组底,然后通過調(diào)用該函數(shù)的call方法,將每個數(shù)組元素作為指定的this值執(zhí)行了那個匿名函數(shù)筐骇。這個匿名函數(shù)的主要目的是給每個數(shù)組元素對象添加一個print方法债鸡,這個print方法可以打印出各元素在數(shù)組中的正確索引號。當(dāng)然铛纬,這里不是必須得讓數(shù)組元素作為this值傳入那個匿名函數(shù)(普通參數(shù)就可以)厌均,目的是為了演示call的用法。
var animals = [ {species: 'Lion', name: 'King'}, {species: 'Whale', name: 'Fail'} ];
for (var i = 0; i < animals.length; i++) { (function (i) { this.print = function () { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(animals[i], i); }
//#0 Lion: King
//#1 Whale: Fail
使用call方法調(diào)用函數(shù)傳參數(shù)
var a = { name:'JSLite.io', //定義a的屬性 say:function(){ //定義a的方法 console.log("Hi,I'm function a!"); } };
function b(name){ console.log("Post params: "+ name); console.log("I'm "+ this.name); this.say(); }
b.call(a,'test'); //Post params: test //I'm JSLite.io //I'm function a!
- apply()
語法與 call() 方法的語法幾乎完全相同告唆,唯一的區(qū)別在于棺弊,apply的第二個參數(shù)必須是一個包含多個參數(shù)的數(shù)組(或類數(shù)組對象)。apply的這個特性很重要(因為這個特性可以做很多事情)擒悬,
apply方法會調(diào)用一個函數(shù)模她,apply方法的第一個參數(shù)會作為被調(diào)用函數(shù)的this值,apply方法的第二個參數(shù)(一個數(shù)組懂牧,或類數(shù)組的對象)會作為被調(diào)用對象的arguments值侈净,也就是說該數(shù)組的各個元素將會依次成為被調(diào)用函數(shù)的各個參數(shù);
在調(diào)用一個存在的函數(shù)時僧凤,你可以為其指定一個 this 對象用狱。 this 指當(dāng)前對象,也就是正在調(diào)用這個函數(shù)的對象拼弃。 使用 apply, 你可以只寫一次這個方法然后在另一個對象中繼承它摇展,而不用在新對象中重復(fù)寫該方法吻氧。
語法:fun.apply(thisArg[, argsArray])
注意:需要注意:Chrome 14 以及 Internet Explorer 9 仍然不接受類數(shù)組對象。如果傳入類數(shù)組對象,它們會拋出異常盯孙。
2.1 參數(shù)
thisArg
同上call的thisArg參數(shù)鲁森。
argsArray
一個數(shù)組或者類數(shù)組對象,其中的數(shù)組元素將作為單獨的參數(shù)傳給fun 函數(shù)振惰。如果該參數(shù)的值為null 或 undefined歌溉,則表示不需要傳入任何參數(shù)。從ECMAScript 5 開始可以使用類數(shù)組對象骑晶。
2.2 例子
function jsy(x,y,z){ console.log(x,y,z); }
jsy.apply(null,[1,2,3]); // 1 2 3
使用apply來鏈接構(gòu)造器的例子
你可以使用apply來給一個對象鏈接構(gòu)造器痛垛,類似于Java. 在接下來的例子中我們會創(chuàng)建一個叫做construct的全局的Function函數(shù),來使你能夠在構(gòu)造器中使用一個類數(shù)組對象而非參數(shù)列表。
Function.prototype.construct = function(aArgs) { var fConstructor = this, fNewConstr = function() { fConstructor.apply(this, aArgs); }; fNewConstr.prototype = fConstructor.prototype; return new fNewConstr(); };
function MyConstructor () { for (var nProp = 0; nProp < arguments.length; nProp++) { console.log(arguments,this) this["property" + nProp] = arguments[nProp]; } }
var myArray = [4, "Hello world!", false];
var myInstance = MyConstructor.construct(myArray);
console.log(myInstance.property1); // logs "Hello world!" console.log(myInstance instanceof MyConstructor); // logs "true" console.log(myInstance.constructor); // logs "MyConstructor"