Avinash Kumar
Avinash Kumar

Reputation: 81

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

  });

Upvotes: 0

Views: 183

Answers (2)

Nikos M.
Nikos M.

Reputation: 8345

this takes a completely different value inside ready function unless you bind this to the function

For example:

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

or use the ES6 arrow functions which take this from the parent scope

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

  });

a third option is to store this to another variable and refer to that variable instead. For example:

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

  });

Explanation: this is a unique variable from the rest (in Object-Oriented Programming). It gets re-assigned to different values (with same name this) based on which function scope it is used. So to keep this to refer to a specific instance inside another function you need to follow one of the approaches above.

Upvotes: 0

brk
brk

Reputation: 50326

First is angular does not need jquery to handle any functionalities. Still , in this case you are getting undefined because using of function key word with $(document). Inside $(document).ready(function () this will get a complete new scope and it does not know what is selectedUrl. You can explore arrow function

Upvotes: 4

Related Questions