2014-02-12 43 views
0

我有这样的javascript代码:使用父范围变量和JavaScript

myApp.factory('Reddit', function($http) { 
    var Reddit = function() { 
    this.items = []; 
    this.busy = false; 
    this.after = ''; 
    }; 

    Reddit.prototype.nextPage = function() { 
    console.log(this.items);// [] 
    $http({method: 'GET', url: url}). 
    success(function(data, status, headers, config) { 
     console.log(this.items); // undefined ?? how to access to items list 
    }) 

如何可以访问到的物品清单在success功能?

+0

成功回调函数'this'是指回调函数,而不是'Reddit'对象,因此'this.items'是未定义的。请参阅@ ogc-nick关于如何避免此问题的答案。 – package

回答

1

尝试在定义它时将其分配给局部变量。该局部变量应该在你的成功函数中定义。

Reddit.prototype.nextPage = function() { 
    console.log(this.items);// [] 
    var localItems = this.items; // if it is defined here, then alias it to a local var (you can rename it to whatever) 
    $http({method: 'GET', url: url}). 
    success(function(data, status, headers, config) { 
     console.log(this.items); // undefined ?? how to access to items list 
     console.log(localItems); // should work 
    }) 

我认为,虽然你会想要访问整个对象在这种情况下,你可以别名this

Reddit.prototype.nextPage = function() { 
    var obj = this; 
    $http({method: 'GET', url: url}). 
    success(function(data, status, headers, config) { 
     obj.items.push('xxx'); 
    }); 

这里是显示一个Reddit对象建立不同的多个实例plunkr items列表:。确保检查控制台。