[Vuejs]-Console returning not function when function is defined

1đź‘Ť

âś…

It’s all because you’re loosing this when you set a timeout, because function(){} doesn’t save the this context, but as arrow functions do, check the difference between them

setTimeout(() => this.backAgain(), 2000)

1đź‘Ť

You should use an arrow function in order to access this context :

  cashOut(){
      clearTimeout(this.tessst);
      this.money = Number(this.money) + Number(this.winning);
      setTimeout(()=>{
        this.backAgain()
      },2000)
    }}

1đź‘Ť

You need to bind this. Arrow function does it for you.
If you are using IE 11 and you don’t have arrow functions, you can bind in this way:

setTimeout(function(){ this.backAgain() }.bind(this), 2000)

In your case, you can bind and execute with call or apply execute:

setTimeout(this.backAgain.call(this), 2000)

1đź‘Ť

this is lost when the callback is called, but you can for example use a local variable in its closure (the usual concept of accessing variables from “outer” blocks surrounding a piece of code extended with the “twist” that the variables can be accessed even after the immediate code which contained them has finished running), which is not lost:

cashOut(){
  clearTimeout(this.tessst);
  this.money = Number(this.money) + Number(this.winning);
  var diz = this;             // <--- store
  setTimeout(function(){
    diz.backAgain();          // <--- use
  },2000)
}}

Leave a comment