Calling function outside the scope in javascript

Asked

Viewed 307 times

2

Follow the code to explain my mistake:

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

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

The getName method returns an error as it cannot find this.ShowName, natural because it is outside the scope. The question is, how do I call the method showName in this situation?

  • 1

    About the variable minha-url, that is not a valid identifier for the JS, although I keep this in my answer, I believe you have another name for the variable as minhaUrl or minha_url

  • yes, it was just to illustrate.

2 answers

4


If you’re using class, are using ES6, then you can use Arrow Functions, which maintains the local scope from which they were declared, thus the this will work in your case.

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

  getName() {
    $.get(minha-url).done(data => this.showName(data.name))
  }
}
  • Man, it worked, thank you very much. If you can give me a link explaining better this scope treatment of Arrow Function. Thanks!

2

You can pass your method directly as callback and with .bind, so run 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, thus:

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

Example of the second working option:

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

  • The problem in option 1 and option 2 that you passed is that you need to create a Function that calls my method because in this Function I will pass the date as parameter. The third option I found a little complex because it writes more code compared to Gabriel Katakura’s solution. But anyway I appreciate the help.

  • @Felipecoelho the third option is an example of the second. And it has the least code of all answers/suggestions. I only wrote code to put an example to work.

  • You’re right, I hadn’t looked in detail. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.