AngularJS/JS如何访问函数外的变量

AngularJS/ JS How do I access variables outside my function?

本文关键字:函数 变量 访问 JS 何访问 AngularJS      更新时间:2023-09-26

我正试图访问函数块中定义的变量np;但是,当我调用this.items.push(plumbers)时,遇到了一些问题。我得到TypeError: Cannot call method push of undefined

myApp.factory('np', function($resource, nearbyPlumbers){
  var np = function(){
    this.items = [];
    this.busy = false;
    this.limit = 5;
    this.offset = 0;
  };
  np.prototype.nextPage = function(){
    if (this.busy) return;
    this.busy = true;
    var temp;
    nearbyPlumbers.nearby({lat: -37.746129599999996, lng: 144.9119861}, function(data){
      angular.forEach(data, function(plumber){
        alert('yay');
        //this.items.push(plumber);
        console.log(plumber);
        console.log(this.items); // <--- This wont work. How do I access this.items
      });
    });
  };
  return np;
});
np.prototype.nextPage = function () {
    if (this.busy) return;
    this.busy = true;
    var temp;
    var that = this; // add this line
    nearbyPlumbers.nearby({
        lat: -37.746129599999996,
        lng: 144.9119861
    }, function (data) {
        angular.forEach(data, function (plumber) {
            that.items.push(plumber); //access using "that"
            console.log(plumber);
            console.log(that.items);
        });
    });
};

我真的很好奇为什么要使用this,因为它将是不同的this,这取决于从哪个范围访问单例。这可以解释你所犯的错误。

我强烈建议阅读Angular中的工厂,然后再看一看代码。服务文档是一个很好的起点,这个问题也很好。