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)


qq_遁去的一_1
浏览 932回答 1
1回答

慕桂英546537

this 指向的问题要么用 es6 箭头函数,要么把var that = this 函数体里用that 替代thisapply 也只是指向了你匿名函数的this
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript