簡體   English   中英

如何在 function (typescript/jquery) 中維護“this”變量

[英]How to maintain “this” variable inside function (typescript/jquery)

I use Jquery in my angular project.I try to access the value of this.selectedUrl but when it jumps into the Jquery ready function it gives UNDEFINED.How to do it?

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)  // gives undefiend
     if(this.selectedUrl=="/home"){
      console.log("this.selectedUrlIf",this.selectedUrl)
     }

  });

首先是 angular 不需要 jquery 來處理任何功能。 盡管如此,在這種情況下,由於使用帶有$(document)function關鍵字,您會變得不確定。 $(document).ready(function () this將得到一個全新的 scope 並且它不知道selectedUrl是什么。您可以探索arrow function

除非您將this thisready

例如:

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));

或使用從父 scope 獲取this ES6 箭頭函數

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是 rest 中的唯一變量(在面向對象編程中)。 根據使用的 function scope 重新分配給不同的值(同名this 因此,要this引用另一個 function 中的特定實例,您需要遵循上述方法之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM