码迷,mamicode.com
首页 > 移动开发 > 详细

Javascript手写call, apply, bind

时间:2019-03-02 18:30:01      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:lse   var   eof   name   getname   ||   context   cat   span   

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

 

Javascript手写call, apply, bind

标签:lse   var   eof   name   getname   ||   context   cat   span   

原文地址:https://www.cnblogs.com/codejoker/p/10462278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!