this 總是返回一個(gè)對(duì)象;
this就是屬性或方法“當(dāng)前”所在的對(duì)象;
如果用一個(gè)對(duì)象調(diào)用一個(gè)函數(shù),那么這個(gè)對(duì)象就是 該函數(shù)里的 this;
改成 call() ,this 就是 call() 的第一個(gè)參數(shù);
箭頭函數(shù)沒有 this ,箭頭函數(shù)內(nèi)外 this 不變,向上找。
!function(){
var view = document.querySelector('#topNavBar')
var controller = {
view: null,
init: function(view){
this.view = view
this.bindEvents()
//轉(zhuǎn)換成 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)
//轉(zhuǎn)換成 controller.init.call(controller,view) ,init 函數(shù)里的 this 就是對(duì)象 controller
}.call()