Javascript:在另一种方法中调用一个方法 [英] Javascript: Call a method inside another method
问题描述
我有一个简单的应用程序,它会触发一个布尔值并将任务设置为完成:
但我希望能够使用Complete All按钮并设置每一项任务都要完成。这里工作正常:
completeAll:function(){
this.tasks.forEach(function(task){
task.completed = true;
});
},
http://codepen.io/anon/pen/avzMYr
但不是直接设置,而是想要使用这样的方法,因为我有很多其他代码需要分开。
completeTask:function(task){
task.completed = true;
completeAll:function(){
this.tasks.forEach(function(task){
this.completeTask(task);
});
},
然而这不起作用,请看这里:
http://codepen.io/anon/pen/EVaMLJ
任何想法如何在completeAll方法中调用completeTask(task)方法?
你的问题是 .forEach()
中的 this
回调与外部不一样。您可以保存这个
的外部值,然后使用该保存的版本获得您想要的内容:
completeAll:function(){
var self = this;
this.tasks.forEach(function(task){
self.completeTask(task);
});
},
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
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
Any idea how to call the "completeTask(task)" method inside of the completeAll method?
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:
completeAll: function() {
var self = this;
this.tasks.forEach(function(task) {
self.completeTask(task);
});
},
这篇关于Javascript:在另一种方法中调用一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!