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
2 Answers
Reset to default 6Your 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
版权声明:本文标题:function - Javascript: Call a method inside another method - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744046222a2581571.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论