我正在阅读有关 ngInfiniteScroll 的内容,而且我是 JS 的新手。
正如我读过的demo nfInfiniteScroll,我很难理解为什么Reddit.nextPage
已转化为Reddit.prototype.nextPage
它已被使用bind()
包装Reddit.prototype.nextPage
的一部分的方法 body 。
这是代码。
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
被分配了一个匿名函数,我需要绑定(bind) this
匿名函数到 this
的Reddit.nextPage
,所以它们引用相同的属性?
但我可以清楚地看到,即使没有 bind()
也可以访问这些属性。方法。请参阅:
if (this.busy) return;
this.busy = true;
我读过一些有关该主题的文章,但没有一篇深入解释它:我真的很困惑。
最佳答案
让我们看看这些函数:
Reddit.prototype.nextPage = function() {
// outer function
...
$http.jsonp(url).success(function(data) {
// inner function
}.bind(this));
};
如果没有绑定(bind),内部函数中的 this
将具有不同的属性,因为它位于另一个上下文中。但是,如果我们调用 bind(this)
,我们就会告诉内部函数从 outer 函数的上下文中使用 this
。
更多信息我推荐this article .
关于javascript - Object.prototype 和 bind() 方法如何协同工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38150557/