`this` in callback points to wrong object

前端 未结 3 1702
长情又很酷
长情又很酷 2021-01-25 08:08

I have this viewModel:

import app = require(\"durandal/app\");
import appViewModel = require(\"appViewModel\");
import dataService = require(\"dataService\");

c         


        
相关标签:
3条回答
  • 2021-01-25 08:18

    You could also do then(this.activateView.bind(this))

    0 讨论(0)
  • 2021-01-25 08:33

    Since you are passing the function to someone else to call in .then(this.activateView); you need to preserve the context yourself, best if you do : .then((view)=>this.activateView(view));

    More about this : https://www.youtube.com/watch?v=tvocUcbCupA

    0 讨论(0)
  • 2021-01-25 08:34

    While you have your answer, the way I prefer is a bit different:

    convert function/method definition - into "property referencing function"

    // instead of class method
    // public activateView(view) {
    
    // use the "property"
    public activateView = (view) => {
        this.activeScreen(view);
    }
    

    That will reduce the need to pass explicit params like this

    .then((view) => this.activateView(view))
    

    because this will work again:

    .then(this.activateView)
    
    0 讨论(0)
提交回复
热议问题