'this'指的是函数内部而不是对象(jQuery)

时间:2017-01-29 11:15:23

标签: jquery loops this

我有以下课程:

function courseOversight() {
  this.courseBlocks = []; // Stores the courseblocks on the page
  this.getCourseBlocks = function() {
    $(".course-block").each(function(){
      var block = new courseBlock();
      this.courseBlocks.push(block);
    });
  }
}

正如您所看到的,我正在尝试使用页面上的courseBlocks填充对象的courseBlocks数组。但是,在each()循环中,'this'指的是我正在添加的课程块,而不是courseOversight对象。如何在不使用现在不可用的'this'关键字的情况下访问courseOversights courseBlocks数组?谢谢!

2 个答案:

答案 0 :(得分:0)

你可以通过分配这个'来解决这个问题。输入之前的变量,如下所示

function courseOversight() {
var _this = this; //Assign 'this' context to a new var
this.courseBlocks = []; // Stores the courseblocks on the page
this.getCourseBlocks = function() {
    $(".course-block").each(function(){
        var block = new courseBlock();
        // Now you can call the following like this.
        // _this.courseBlocks.push(block);
        this.courseBlocks.push(block);
    });
}
}

答案 1 :(得分:0)

您可以将this保存到另一个变量(p.e。self



function courseBlock(){
}

function courseOversight() {
  var self = this;
  self.courseBlocks = []; // Stores the courseblocks on the page
  self.getCourseBlocks = function() {
    $(".course-block").each(function(){
      var block = new courseBlock();
      self.courseBlocks.push(block);
    });
  }
  self.getCourseBlocks();
  console.log("Tests: ", self.courseBlocks);
}
courseOversight();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="course-block">Block 1</div>
  <div class="course-block">Block 2</div>
  <div class="course-block">Block 3</div>
</div>
&#13;
&#13;
&#13;