admin管理员组

文章数量:1355675

I have a simple app, that triggers a boolean and sets a task to pleted:

But I want to be able use a "Complete All" Button and set every task to plete. This here works fine:

  pleteAll: function() {
    this.tasks.forEach(function(task) {
      taskpleted = true;
    });
  },

But instead of setting it directly, I would like to use a method that is called like this, because I have a lot of other code that needs to be separated.

  pleteTask: function(task) {
    taskpleted = true;
  },

  pleteAll: function() {
    this.tasks.forEach(function(task) {
      thispleteTask(task);
    });
  },

Yet this does not work, see here:

Any idea how to call the "pleteTask(task)" method inside of the pleteAll method?

I have a simple app, that triggers a boolean and sets a task to pleted:

But I want to be able use a "Complete All" Button and set every task to plete. This here works fine:

  pleteAll: function() {
    this.tasks.forEach(function(task) {
      task.pleted = true;
    });
  },

http://codepen.io/anon/pen/avzMYr

But instead of setting it directly, I would like to use a method that is called like this, because I have a lot of other code that needs to be separated.

  pleteTask: function(task) {
    task.pleted = true;
  },

  pleteAll: function() {
    this.tasks.forEach(function(task) {
      this.pleteTask(task);
    });
  },

Yet this does not work, see here:

http://codepen.io/anon/pen/EVaMLJ

Any idea how to call the "pleteTask(task)" method inside of the pleteAll method?

Share Improve this question asked Sep 5, 2015 at 22:59 LoveAndHappinessLoveAndHappiness 10.2k22 gold badges74 silver badges107 bronze badges 1
  • 1 Wele to JS's interpretation of what this is. It isn't always that, unless you explicitly close over it. – Dave Newton Commented Sep 5, 2015 at 23:02
Add a ment  | 

2 Answers 2

Reset to default 6

Your problem is that the value of this inside the .forEach() callback is not the same as what it is outside. You can save the outer value of this and then use that saved version to get what you want:

  pleteAll: function() {
    var self = this;
    this.tasks.forEach(function(task) {
      self.pleteTask(task);
    });
  },

You could use Bind for setting the this value in methods like this:

pleteAll: function() {
  this.tasks.forEach(function(task) {
    this.pleteTask(task);
  }.bind(this));
}

本文标签: functionJavascript Call a method inside another methodStack Overflow