lundi 19 septembre 2016

Why this is not giving correct context while using promise?

I need to use Promise to execute things order in the following code. My actual save is ajax POST and want to call execute only after that successful POST. Everything is working fine, but the problem is that I can't access the actual this variable, inside execute function. console.log(this.abc); gives me undefined why?.

  function MyClass(context) {
      this.abc  = "xyz";
  };

  MyClass.prototype.save = function() {
    console.log(" saving");
    return new Promise(function(resolve, reject){
      resolve();
    });
  };

  MyClass.prototype.execute = function() {
    console.log(" executing");
    console.log(this.abc);
  };

  var myInstance = new MyClass();

  window.addEventListener('keydown', function(e) {
    e.preventDefault();
    if(event.ctrlKey & (event.which==83)) {
      myInstance.save();
    } else if (event.ctrlKey && (event.which==69)) {
      myInstance.save().then(myInstance.execute);
    }
  }, false);

Aucun commentaire:

Enregistrer un commentaire