2 回答

TA貢獻1864條經驗 獲得超6個贊
首先是 Angular 不需要 jquery 來處理任何功能。function
不過,在這種情況下,您會因為使用關鍵字 with而變得不確定$(document)
。里面 $(document).ready(function ()
this
會得到一個全新的范圍,它不知道是什么selectedUrl
。你可以探索arrow function

TA貢獻1809條經驗 獲得超8個贊
thisready除非您綁定到函數,否則函數內部會采用完全不同的值this
例如:
this.selectedUrl = this.router.url
console.log("this.selectedUrl",this.selectedUrl) // gives value i.e /home
$(document).ready(function () {
console.log("this.selectedUrl",this.selectedUrl) // this is now available
if(this.selectedUrl=="/home"){
console.log("this.selectedUrlIf",this.selectedUrl)
}
}.bind(this));
或使用從父作用域獲取的ES6 箭頭函數this
this.selectedUrl = this.router.url
console.log("this.selectedUrl",this.selectedUrl) // gives value i.e /home
$(document).ready(()=>{
console.log("this.selectedUrl",this.selectedUrl) // this is now available
if(this.selectedUrl=="/home"){
console.log("this.selectedUrlIf",this.selectedUrl)
}
});
第三種選擇是存儲this到另一個變量并改為引用該變量。例如:
var that = this; // store to variable
this.selectedUrl = this.router.url
console.log("this.selectedUrl",this.selectedUrl) // gives value i.e /home
$(document).ready(function () {
console.log("this.selectedUrl",that.selectedUrl) // this is now available via that variable
if(that.selectedUrl=="/home"){
console.log("this.selectedUrlIf",that.selectedUrl)
}
});
解釋: this是其余變量中的唯一變量(在面向對象編程中)。根據使用的函數范圍,它被重新分配給不同的值(具有相同的名稱this) 。因此,要繼續this引用另一個函數中的特定實例,您需要遵循上述方法之一。
添加回答
舉報