underscore里面的throttle,执行func的时候为什么要用apply绑定

underscore源码地址: https://github.com/jashkenas/... 852行

    function factory(name, color) {
      this.name = name;
      this.color = color;
    }    
    
    factory.prototype.init = function() {
      document.querySelector('.parent').addEventListener('scroll', throttle(function(){
        console.log(this.name, this.color)
      }, 1000, {leading: false, trailing: true}))
    }


    var product = new factory('jack', 'white')

    product.init() 

滚动时,打印的值为 undefined, undefined

而源码中执行的时候,用了apply绑定this的作用域

result = func.apply(context, args);

但这样好像并没有什么用,所以这里为什么不直接用 func(args)

阅读 2.2k
1 个回答

this 指向的问题

要么用 es6 箭头函数,要么把var that = this 函数体里用that 替代this

apply 也只是指向了你匿名函数的this

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题