本文章用于个人笔记-内容参考于掘金
- 先看一下
call
、apply
、bind
的应用
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
- 手写实现-
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
}
-手写实现-apply
Function.prototype.myApply = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
context.fn = this
let result
// 处理参数和 call 有区别
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
- 手写实现-
bind
Function.prototype.myBind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
const _this = this
const args = [...arguments].slice(1)
// 返回一个函数
return function F() {
// 因为返回了一个函数,我们可以 new F(),所以需要判断
if (this instanceof F) {
return new _this(...args, ...arguments)
}
return _this.apply(context, args.concat(...arguments))
}
}