本文章用于個(gè)人筆記-內(nèi)容參考于掘金
- 先看一下
call、apply、bind的應(yīng)用
function a(key,value){
console.log(this.name)
console.log(key)
console.log(value)
}
var name = 'lv'
var obj = {
name: 'yong'
}
a.call(obj,1,2)//'yong' 1 2
a.call(obj)//'yong' undefined undefined
a.apply(obj,[1,2])//'yong' 1 2
var b = a.bind(obj,1,2)
b()//'yong' 1 2
- 手寫實(shí)現(xiàn)-
call
Function.property.myCall = function(context){
if(typeof this != 'function'){
return throw new TypeError('Error')
}
context = context || window
context.fn = this
let args = context.slice(1)
const result = context.fn(...arg)
delete context.fn
return result
}
-手寫實(shí)現(xiàn)-apply
Function.prototype.myApply = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
context.fn = this
let result
// 處理參數(shù)和 call 有區(qū)別
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
- 手寫實(shí)現(xiàn)-
bind
Function.prototype.myBind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
const _this = this
const args = [...arguments].slice(1)
// 返回一個(gè)函數(shù)
return function F() {
// 因?yàn)榉祷亓艘粋€(gè)函數(shù),我們可以 new F(),所以需要判斷
if (this instanceof F) {
return new _this(...args, ...arguments)
}
return _this.apply(context, args.concat(...arguments))
}
}