Javascript手写call, apply, bind

call方法实现

 1         Function.prototype.mycall = function(context) {
 2             var context = context || window
 3             context.fn = this
 4             var args = [...arguments].slice(1)
 5             var result = context.fn(...args)
 6             delete context.fn
 7             return result
 8         }
 9         var a = {name: 'ss'}
10         function getName(){console.log(this.name)}
11         getName.mycall(a) // 'ss'

apply方法实现

        Function.prototype.myapply = function(context) {
            var context = context || window
            context.fn = this
            var result
            if (arguments[1]) {
                result = context.fn(...arguments[1])
            } else {
                result = context.fn()
            }
            delete context.fn
            return result
        }
        var a = {name: 'ss'}
        function getName(){console.log(this.name)}
        getName.apply(a) // 'ss'    

bind实现

Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  var _this = this
  var 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))
  }
}

 

posted on 2019-03-02 18:19  时光游弋  阅读(169)  评论(0编辑  收藏  举报