this 总是返回一个对象;
this就是属性或方法“当前”所在的对象;
如果用一个对象调用一个函数,那么这个对象就是 该函数里的 this;
改成 call() ,this 就是 call() 的第一个参数;
箭头函数没有 this ,箭头函数内外 this 不变,向上找。
!function(){
var view = document.querySelector('#topNavBar')
var controller = {
view: null,
init: function(view){
this.view = view
this.bindEvents()
//转换成 this.bindEvents.call(this),bindEvents() 里的 this 就是左边的 this
},
bindEvents: function(){
window.addEventListener('scroll', (x) => {
if(window.scrollY > 0){
this.active()
}
else{
this.deactive()
}
})
},
active: function(){
this.view.classList.add('sticky')
},
deactive: function(){
this.view.classList.remove('sticky')
}
}
controller.init(view)
//转换成 controller.init.call(controller,view) ,init 函数里的 this 就是对象 controller
}.call()