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

发布于 2022-09-07 20:27:37 字数 779 浏览 21 评论 0

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

总攻大人 2022-09-14 20:27:37

this 指向的问题

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文