javascript - Object.prototype 和 bind() 方法如何协同工作

标签 javascript angularjs prototype bind factory

我正在阅读有关 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匿名函数到 thisReddit.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/

相关文章:

javascript - Css 悬停缩放效果不起作用

javascript - 是否可以用 jasmine 模拟网络故障来模拟 ajax 请求?

javascript - AngularJS - 表单验证,v 1.4.8

javascript - 添加 href 属性后,ng-click 不适用于 Internet Explorer 中的 anchor 标记

javascript - 在 JavaScript 中创建派生类的多个实例

javascript - 关于 JavaScript 数组原型(prototype)

javascript - 如何在reactjs中使用原型(prototype)

javascript - 这个 jQuery 函数调用是什么?

javascript - 引用错误: assignment to undeclared variable petsPrice_cal

javascript - 如何使用 Php session 变量作为 Angular Js 数据