call咖为,apply秕狰、bind的區(qū)別:
bind綁定this的指向之后,不會(huì)立即調(diào)用當(dāng)前函數(shù)躁染,而是將函數(shù)返回鸣哀。
而call,apply綁定this指向后會(huì)立即調(diào)用褐啡。
如果我們?cè)诓恢朗裁磿r(shí)候會(huì)調(diào)用函數(shù)的時(shí)候诺舔,需要改變this的指向鳖昌,那么只能使用bind备畦。
比如:在定時(shí)器中,我們想改變this的指向许昨,但是又不能立即執(zhí)行懂盐,需要等待2秒,這個(gè)時(shí)候只能使用bind來(lái)綁定this糕档。
setInterval(function(){
// ...
}.bind(this), 2000);
一莉恼、Apply
方法重用
通過(guò) apply() 方法,您能夠編寫用于不同對(duì)象的方法速那。
JavaScript apply() 方法
apply() 方法與 call() 方法非常相似:
在本例中俐银,person 的 fullName 方法被應(yīng)用到 person1:
實(shí)例
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName: "Bill",
lastName: "Gates",
}
person.fullName.apply(person1); // 將返回 "Bill Gates"
二、call
call函數(shù)
在Function.prototype上掛載一個(gè)newCall函數(shù)表示是對(duì)call的模擬端仰,具體邏輯看注釋
Function.prototype.newCall = function(context){
// 1 判斷context是否為object捶惜,如果是object就代表可能是Object 或者 null,如果不是就賦值一個(gè)空對(duì)象
if (typeof context === 'object') {
context = context || window // context 如果是null就會(huì)賦值為window
} else {
context = Object.create(null)
}
// 2 在context下掛載一個(gè)函數(shù)荔烧,函數(shù)所在的key隨機(jī)生成吱七,防止context上已有同名key
var fn = +new Date() + '' + Math.random() // 用時(shí)間戳+隨機(jī)數(shù)拼接成一個(gè)隨機(jī)字符串作為一個(gè)新的key
context[fn] = this
// 3 newCall如果還有其他的參數(shù)傳入也要考慮用到
var args = []
for(var i = 1; i < arguments.length; i++) {
args.push('arguments['+ i + ']')
}
// 4 重點(diǎn)在這里,執(zhí)行context[fn]這個(gè)函數(shù)鹤竭,只能用eval踊餐,因?yàn)閚ewCall的入?yún)?shù)不確定
var result = eval('context[fn]('+args+')') // args是一個(gè)數(shù)組,但是當(dāng)它和字符串相加時(shí)自動(dòng)調(diào)用內(nèi)部的toString方法轉(zhuǎn)成字符串
delete context[fn] // 用完后從context上刪除這個(gè)函數(shù)
// 5 返回結(jié)果
return result
}
原理:
在要掛載的對(duì)象context上臨時(shí)添加一個(gè)方法 f
用eval執(zhí)行這個(gè)臨時(shí)添加的方法f臀稚,并拿到執(zhí)行后的結(jié)果result
刪除這個(gè)額外的方法f吝岭,并返回執(zhí)行結(jié)果result
帶參數(shù)的 apply() 方法
apply() 方法接受數(shù)組中的參數(shù):
實(shí)例
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);
與 call() 方法對(duì)比:
實(shí)例
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;