語法
- apply()主要用途是改變this的指向
- 舉個例子
let obj = {
name: 'Amy',
age: 18
}
function conNAme() {
console.log(this.name)
}
function count() {
console.log(this.age + 1)
}
count.apply(obj) //19
conNAme.apply(obj) //Amy
其實上面的代碼就相當(dāng)于(改變函數(shù)中的this指向,指向了obj):
let obj = {
name: 'Amy',
age: 18,
count() {
console.log(this.age + 1)
},
conNAme() {
console.log(this.name)
}
}
obj.count()
obj.conNAme()
手寫
Function.prototype.myApply = function(thisValue,arr = []) {
let _thisValue = thisValue || window //當(dāng)沒有傳this則默認(rèn)是window調(diào)用該方法
_thisValue.fn = this //這里的this指調(diào)用該方法的函數(shù)括尸,例如上面的例子如果是count函數(shù)調(diào)用圾浅,則this指的是count
//這個代碼的意思就是:_thisValue就是上面例子的obj线召,也就是obj.fn = count(){} 就是在該對象中增添該方法
let result //用以接收返回值
if(arr.length == 0) {
_thisValue.fn() //沒有傳參數(shù)則直接調(diào)用該方法
} else {
let newAguiments = []
for(let i = 0;i < arr.length;i++) {
newAguiments.push('arr[' + i + ']')
//因為假如直接傳arr[i]的話凡涩,如果傳的參數(shù)是'你好',2仆嗦,3炭剪,newAguiments就是['你好',2,3],
//在eval中是eval('_thisValue.fn(你好,2,3)') 你好 這個字符串沒有加雙/單引號 可見 如果存在字符串這種情況的話就會報錯
}
result = eval('_thisValue.fn(' + newAguiments + ')') //eval函數(shù)可執(zhí)行字符串中的語句
}
delete _thisValue.fn //刪除對象中的該方法因為不能改變原本的對象
return result
}
let obj = {
name: 'Amy',
age: 18
}
function conNAme(a,b,c) {
console.log(this.name),
console.log(a,b,c)
}
function count() {
console.log(this.age + 1)
}
count.myApply(obj) //19
conNAme.myApply(obj,['xiaosi',34,55]) //Amy xiaosi 34 55
另外一個方法
Function.prototype.myApply = function(thisValue,arr = []) {
let _thisValue = thisValue || window //當(dāng)沒有傳this則默認(rèn)是window調(diào)用該方法
_thisValue.fn = this //這里的this指調(diào)用該方法的函數(shù)练链,例如上面的例子如果是count函數(shù)調(diào)用,則this指的是count
//這個代碼的意思就是:_thisValue就是上面例子的obj奴拦,也就是obj.fn = count(){} 就是在該對象中增添該方法
let result //用以接收返回值
if(arr.length == 0) {
result = _thisValue.fn() //沒有傳參數(shù)則直接調(diào)用該方法
} else {
result = _thisValue.fn(...arr)
}
delete _thisValue.fn //刪除對象中的該方法因為不能改變原本的對象
return result
}
call()
function myCall(thisValue,prams) {
let _thisValue = thisValue || window
_thisValue.fn = this
const res = _thisValue.fn(...prams)
delete _thisValue.fn
return res
}