【发布时间】:2016-07-01 16:59:38
【问题描述】:
我正在阅读有关 ngInfiniteScroll 的信息,并且我是 JS 的新手。
当我阅读了 nfInfiniteScroll 的 demo 时,我很难理解为什么 Reddit.nextPage 已被转换为 Reddit.prototype.nextPage 并且已使用 bind() 方法来包装 Reddit.prototype.nextPage 正文的一部分。
这里是代码。
myApp.controller('DemoController', function($scope, Reddit) {
$scope.reddit = new Reddit();
});
// Reddit constructor function to encapsulate HTTP and pagination logic
myApp.factory('Reddit', function($http) {
var Reddit = function() {
this.items = [];
this.busy = false;
this.after = '';
};
Reddit.prototype.nextPage = function() {
if (this.busy) return;
this.busy = true;
var url = "https://api.reddit.com/hot?after=" + this.after + "&jsonp=JSON_CALLBACK";
$http.jsonp(url).success(function(data) {
var items = data.data.children;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i].data);
}
this.after = "t3_" + this.items[this.items.length - 1].id;
this.busy = false;
}.bind(this));
};
return Reddit;
});
我刚刚明白:通过使用this,我可以访问Reddit 对象中的属性。
是否只是因为var Reddit被分配了一个匿名函数,我需要将匿名函数的this绑定到Reddit.nextPage的this,所以它们引用相同的属性?
但我可以清楚地看到,即使没有 bind() 方法,也可以访问这些属性。见:
if (this.busy) return;
this.busy = true;
我已经阅读了一些关于该主题的文章,但没有一篇深入解释它:我真的很困惑。
【问题讨论】:
标签: javascript angularjs prototype bind factory