Call function out of scope in javascript

2

Follow the code to explain my error:

class Cliente {
showName(name) {
    alert(name)
}

getName(){
  $.get(minha-url)
  .done(function(data) {
    this.showName(data.name)
  })
}
}

The getName method returns an error because it does not find this.ShowName , naturalemnte because it is out of scope. The question is, how do I call the showName method in this situation?

    
asked by anonymous 03.01.2017 / 19:23

2 answers

4

If you are using class , you are using ES6 , then you can use Arrow Functions , which retains the local scope from where it was declared, so this will work for you.

class Cliente {
  showName(name) {
    alert(name)
  }

  getName() {
    $.get(minha-url).done(data => this.showName(data.name))
  }
}
    
03.01.2017 / 19:32
2

You can pass your method directly as callback and with .bind , so it runs in the scope you need:

class Cliente {
    showName(data) {
        alert(data.name);
    }

    getName() {
        $.get('/url').done(this.showName.bind(this));
    }
}

If you are using a Babel compiler that accepts TC39 proposals you can use Public Class Fields , like this:

class Cliente {
    showName = ({name}) => alert(name);
    getName() {
        $.get('/url').done(this.showName);
    }
}

Example of the second option to work:

class Cliente {
    showName = ({name}) => alert(name);
    getName() {
        $.get('/url').done(this.showName);
    }
}

// estas linhas são só para simular o que '$' faz:
let $ = function() {};
$.prototype.get = function() {return this;};
$.prototype.done = function(fn) {
    fn.call(window, {name: 'teste!'});
};
$ = new $();

new Cliente().getName();
    
03.01.2017 / 19:36