美文网首页
手动实现call apply bind

手动实现call apply bind

作者: BingeryLamb | 来源:发表于2020-01-16 13:47 被阅读0次

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')

相关文章

网友评论

      本文标题:手动实现call apply bind

      本文链接:https://www.haomeiwen.com/subject/imdfzctx.html