简体   繁体   English

Javascript:在另一个方法中调用一个方法

[英]Javascript: Call a method inside another method

I have a simple app, that triggers a boolean and sets a task to completed: 我有一个简单的应用程序,它触发一个布尔值并将任务设置为完成:

But I want to be able use a "Complete All" Button and set every task to complete. 但我希望能够使用“全部完成”按钮并完成每项任务。 This here works fine: 这在这里工作正常:

  completeAll: function() {
    this.tasks.forEach(function(task) {
      task.completed = true;
    });
  },

http://codepen.io/anon/pen/avzMYr 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. 但是我不想直接设置它,而是想使用这样调用的方法,因为我有很多其他需要分离的代码。

  completeTask: function(task) {
    task.completed = true;
  },

  completeAll: function() {
    this.tasks.forEach(function(task) {
      this.completeTask(task);
    });
  },

Yet this does not work, see here: 但这不起作用,请看这里:

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

Any idea how to call the "completeTask(task)" method inside of the completeAll method? 知道如何在completeAll方法中调用“completeTask(task)”方法吗?

Your problem is that the value of this inside the .forEach() callback is not the same as what it is outside. 你的问题是,价值this里面.forEach()回调是不一样的,因为它是什么以外。 You can save the outer value of this and then use that saved version to get what you want: 您可以保存外值this ,然后使用该保存的版本,以获得你想要的东西:

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

You could use Bind for setting the this value in methods like this: 你可以使用Bindthis的方法中设置this值:

completeAll: function() {
  this.tasks.forEach(function(task) {
    this.completeTask(task);
  }.bind(this));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM