方法定義:
調(diào)用一個(gè)對(duì)象的一個(gè)方法,以另一個(gè)對(duì)象替換當(dāng)前對(duì)象。
- 共同點(diǎn)
都可以用來代替另一個(gè)對(duì)象調(diào)用一個(gè)方法,第一個(gè)參數(shù)都是用來執(zhí)行運(yùn)行環(huán)境,this 會(huì)被指定為當(dāng)前調(diào)用對(duì)象
關(guān)于第一個(gè)參數(shù)供常,輸入類型不同,對(duì)應(yīng)的this也不一樣,如下:
function a(){
console.log(this);
}
a.call();//window
a.call(null);//window
a.call(undefined);//window
a.call(1);//Number
a.call('aaa');//String
a.call(true);//Boolean
a.call(a);//function(){}
a.call({'a':'b'});//Object{}
- 不同點(diǎn)
call(),有多個(gè)參數(shù)
apply()只有兩個(gè)參數(shù)鸡捐,第二個(gè)參數(shù)是一個(gè)數(shù)組
用法
- 一個(gè)簡(jiǎn)單的例子:
獲取數(shù)組中最大值和最小值,
var num=[3,23,543,2,52,-1000];
var maxNum=Math.max.apply(this,num);
var minNum=Math.min.call(this,num[0],num[1],num[2],num[3],num[4],num[5]);
不確定有幾個(gè)參數(shù)的時(shí)候使用
function n(){
console.log.apply(this,arguments)
}
// n(1,3,'a','',{},true);
call()傳入 的第一個(gè)參數(shù)作為 this栈暇,傳入的第二個(gè)以及以后的參數(shù)加上綁定函數(shù)運(yùn)行時(shí)本身的參數(shù)按照順序作為原函數(shù)的參數(shù)來調(diào)用原函數(shù),看代碼進(jìn)行理解
function eat(x,y) {
console.log(x+y);
}
function drink(x,y) {
console.log(x-y);
}
drink.call(eat,3,2);//1
eat.call(drink,3,2);//5
擴(kuò)展bind()方法
參數(shù)用法類似于call,但call/apply 是立刻調(diào)用函數(shù)的箍镜,bind 是返回一個(gè)函數(shù)源祈,然后可以在其他時(shí)候調(diào)用。
this.x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
console.log(module.getX()); // 81
var retrieveX = module.getX;
console.log(retrieveX());//9, 因?yàn)?this 指向全局對(duì)象
var boundGetX = retrieveX.bind(module);
console.log(boundGetX()); // 81
- 比較
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
// call
person.hello.call(person, "world"); //James Smith says hello world
// bind
var helloFunc = person.hello.bind(person);
helloFunc("world"); //James Smith says hello world