call apply
Function.prototype.myCall = function(context){
context = context ? Object(context) : window
context.fn = this
let args = [...arguments].slice(1)
let result = context.fn(...args)
delete context.fn
return result
}
Function.prototype.myApply = function(context, arr){
context = context ? Object(context) : window
context.fn = this
var result
result = arr ? context.fn(...arr) : context.fn()
delete context.fn;
return result
}
测试
var value = 1
var obj = {
value: 2
}
function func(name, age) {
console.log(name)
console.log(age)
console.log(this.value)
}
func.myApply(null) //1
func.myApply(obj, ['kevin', 18]) // 'kevin' 18 2
bind
Function.prototype.myBind = function(context, ...args){
return (...innerArgs) => {
this.call(context, ...args, ...innerArgs)
}
}
测试
const obj = {
name: "harden"
};
var name = 'westbrook'
function fn(...msg) {
console.log(this.name);
console.log(...msg);
}
var f = fn.myBind(null, 'hello')
f('thunder')
网友评论