jQuery window.scroll函数内的变量作用域问题咨询
解决jQuery scroll回调中的变量作用域问题
这个问题我之前也踩过坑,核心原因是事件回调函数里的this指向发生了变化:在$window.scroll()的回调里,this默认绑定的是触发事件的window对象,而不是你的someSettings实例,所以才会输出undefined。下面给你三种常用的解决方案:
方法1:保存this到变量(兼容性最好)
在doWork方法里,先把当前指向someSettings的this存到一个变量(比如self或者that),然后在scroll回调里用这个变量访问result:
doWork: function($html, $window, $someElement){ console.log('inside do work ', this.result); //输出true var self = this; // 保存当前的this指向 $window.scroll(function(){ console.log('inside scroll ', self.result); //现在能正确拿到true了 }) }
方法2:使用ES6箭头函数(最简洁)
箭头函数不会创建自己的this,它会继承外层作用域的this指向,所以直接在scroll回调里用箭头函数就行:
doWork: function($html, $window, $someElement){ console.log('inside do work ', this.result); //输出true $window.scroll(() => { console.log('inside scroll ', this.result); //箭头函数继承外层的this,输出true }) }
注意:这个方法需要环境支持ES6,如果你要兼容老浏览器(比如IE11及以下),建议用方法1。
方法3:使用bind()手动绑定this
通过Function.prototype.bind()方法,把scroll回调的this强制绑定到someSettings实例:
doWork: function($html, $window, $someElement){ console.log('inside do work ', this.result); //输出true $window.scroll(function(){ console.log('inside scroll ', this.result); //输出true }.bind(this)) // 绑定this到当前的someSettings对象 }
另外再确认一下:你的trigger()方法确实已经被调用了吧?从你说的doWork里直接打印this.result是true来看,应该是已经调用过了,但如果后续遇到问题,这也是个可以排查的点。
内容的提问来源于stack exchange,提问作者kittu
相关产品推荐
相关产品推荐

