Javascript 如何从回调函数中获取变量的值?

Javascript 如何从回调函数中获取变量的值?,javascript,angularjs,cordova,Javascript,Angularjs,Cordova,我想从回调函数中获取联系人值 如何让我的this.recherche=联系人 App.provider('ContactsP', function() { this.$get = function() { return function(search) { console.log('Factory ContactsCtrl RECHERCHE : ' + search); this.recherche = []; this.options = new Conta

我想从回调函数中获取联系人值

如何让我的
this.recherche=联系人

App.provider('ContactsP', function() {

this.$get = function() {
  return function(search) {

    console.log('Factory ContactsCtrl RECHERCHE : ' + search);

    this.recherche = [];
    this.options = new ContactFindOptions();
    this.options.filter = search;
    this.options.multiple = true;
    this.fields = ["displayName", "name", "phoneNumbers"];

    navigator.contacts.find(this.fields, function(contacts) {

      //I want to put contacts into this.recherche but that doesn't work....

     this.recherche = contacts; return contacts;

    }, function(e) {
      console.log("Error finding contacts " + e.code)
    }, this.options);

  };
};

问题是,当您在回调中时,对
的引用不是您的封闭对象。您需要在对象的上下文中使用来传递

navigator.contacts.find(this.fields, angular.bind(this, function(contacts) {

      //I want to put contacts into this.recherche but that doesn't work....

     this.recherche = contacts; return contacts;

    }), function(e) {
      console.log("Error finding contacts " + e.code)
    }, this.options);

您使用的是什么javascript库?我不会工作,因为“this”是另一个上下文。您可以将“this”存储在一个变量中,并在回调中使用它。它看起来像
。find
my可能是一个异步函数。那样的话,看一看。嗨,谢谢。在安格拉斯和科尔多瓦。菲利克斯:我试着告诉你。