Currently, I am delving into ngInfiniteScroll while being a novice in JavaScript. Upon reviewing the demo of ngInfiniteScroll, I find it quite challenging to comprehend why Reddit.nextPage
has been altered to Reddit.prototype.nextPage
, and how the bind()
method is utilized to encapsulate a segment of the Reddit.prototype.nextPage
function.
Below is the code snippet:
myApp.controller('DemoController', function($scope, Reddit) {
$scope.reddit = new Reddit();
});
// Reddit constructor function for handling HTTP requests 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;
});
I've recently grasped the concept that utilizing this
allows access to properties within the Reddit
object.
Could it be that because var Reddit
is assigned an anonymous function, I need to bind the this
from the anonymous function to the this
in Reddit.nextPage
so they refer to the same properties?
However, it appears feasible to access those properties even without using the bind()
method. Consider the following example:
if (this.busy) return;
this.busy = true;
I have scoured through several articles on this topic but none provide an in-depth explanation, leaving me utterly confused.