在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ underscore里面的throttle,執(zhí)行func的時候為什么要用appl

underscore里面的throttle,執(zhí)行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

而源碼中執(zhí)行的時候,用了apply綁定this的作用域

result = func.apply(context, args);

但這樣好像并沒有什么用,所以這里為什么不直接用 func(args)

回答
編輯回答
情殺

this 指向的問題

要么用 es6 箭頭函數(shù),要么把var that = this 函數(shù)體里用that 替代this

apply 也只是指向了你匿名函數(shù)的this

2018年2月27日 02:52