美文网首页
bind,call,apply的代码实现

bind,call,apply的代码实现

作者: 迦叶凡 | 来源:发表于2019-03-20 21:00 被阅读0次

前言

bind,call,apply三者共同点是都可以改变函数的执行上下文,区别在于bind会返回一个新的函数,而call和apply不会返回的新的函数,而是立即执行函数。

正文

call的代码实现

Function.prototype.call = function (context) {
    context = context || window
    context.fn = this
    //let argus = [...arguments].slice(1)
    //let result = context.fn(...argus)
    let argus = []
    for(var i=1, var len=arguments.length; i<len; i++){
        argus.push('arguments['+i+']')
    }
    let result = eval('context.fn('+argus+')')
    delete context.fn
    return result
}

apply的代码实现

Function.prototype.apply = function (context, array) {
   context = context ? Object(context) : window
   context.fn = this
   let result
   if (!array) {
      result = context.fn()
   } else {
      result = context.fn(...array)
   }
   delete context.fn
   return result
}

bind的代码实现

Function.prototype.bind = function (context) {
    if (typeof this !== 'function') {
        throw new Error('please use bind by function!')
    } 
    let self = this
    let argus1 = [...arguments].slice(1)
    let fb = function () {}
    function fBind () {
        let argus2 = [...arguments]
        return self.apply(this instanceof fb ? this : context, [...argus1, ...argus2])
    }
    fb.prototype = this.prototype
    fBind.prototype = new fb()
    return fBind
}

相关文章

  • js中apply/call/bind

    apply/call/bind 使用apply/call/bind改变 this 指向的 实现过程 apply 使...

  • this 相关问题

    问题1: apply、call 、bind有什么作用,什么区别 apply call bind 问题2: 以下代码...

  • js继承

    问题1: apply、call 、bind有什么作用,什么区别 apply/call/bind 问题2: 以下代码...

  • call.apply.bind实现

    call实现 apply实现 bind实现 new实现

  • JS进阶知识点和常考面试题

    手写 call、apply 及 bind 函数 涉及面试题:call、apply 及 bind 函数内部实现是怎么...

  • apply call bind 的实现

    我们知道apply call bind 都是改变this的指向的,我们首先看apply call的实现。call...

  • js apply ,call,bind

    apply 绑定数组call为对象 不用bind的代码 使用 apply与call是立即执行的而bind返回的是一...

  • 面试知识点

    1、call/apply/bind。重点解释bind的应用 JavaScript中call,apply,bind方...

  • 一篇就够-call\apply\bind的详解和实现

    call\apply\bind用法 call、apply、bind都是用于改变this指向,并且可以通过call、...

  • 前端面试题总结

    Function.prototype.bind实现 JS中的call、apply、bind方法thisObj的取值...

网友评论

      本文标题:bind,call,apply的代码实现

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