`this.some_property` 在匿名回调函数中变为未定义 [英] `this.some_property` becomes undefined inside anonymous callback function
问题描述
所以我不太明白为什么变量 this.tasks 在我的目标对象中的 add 事件侦听器中变得未定义.我有一种感觉,它可能与异步编程有关(我仍然不完全理解).抱歉,我是个 JS 菜鸟,但如果你们能向我解释我做错了什么,以及什么可能是更好的解决方案,那就太棒了!谢谢.
So I can't quite figure out why the variable this.tasks becomes undefined inside of the add event listener I have inside of my goal object. I have a feeling it might have something to do with asynchronous programming(which I still don't fully understand). Sorry I'm a bit of a JS noob, but if you guys could explain to me what I'm doing wrong and what might be a better solution that would be awesome! Thanks.
function Goal(name) {
this.gDiv = document.createElement('div');
this.name = name || "goal";
this.tasks = document.createElement('ul');
//Sets the styling and content and adds it to the parent element
this.initialize = function() {
this.gDiv.className = "default";
this.gDiv.setAttribute("id", this.name);
this.gDiv.innerHTML = this.name;
elem.appendChild(this.gDiv);
this.gDiv.parentNode.insertBefore(this.tasks, this.gDiv.nextSibling);
this.tasks.style.display = "none";
};
//Creates a list underneath the a dive associated with the Goal object
this.addTask = function(task) {
var newLi = document.createElement('li');
newLi.innerHTML = task;
this.tasks.appendChild(newLi);
};
this.gDiv.addEventListener('click', function(){
alert(this.tasks);
});
}
谢谢各位!你们都回答了我的问题!我一直在挠头一段时间.给大家点赞!
Thank you guys! You all answered my question! I'd been scratching my head at this for a while. Kudos to you all!
推荐答案
当您输入匿名闭包并且this"发生变化时,范围会发生变化.你可以通过这样做来破解它
The scope changes when you enter that anonymous closure and 'this' changes. You can hack around it by doing
var self = this;
然后使用 self 代替 this(例如):
And then using self in place of this (eg):
function Goal(name) {
var self = this;
/* ... */
this.gDiv.addEventListener('click', function(){
alert(self.tasks);
});
如果您使用 jQuery,您可以做一些更好的事情:
If you're using jQuery you could do something nicer:
this.gDiv.addEventListener('click', $.proxy(function() {
alert(this.tasks);
}, this));
无论哪种方式都很好.
在 ES6 中,可以使用箭头函数代替,因为它们不绑定自己的this",所以它变得更加简单:
In ES6, arrow functions can be used instead as they don't bind their own "this", so it becomes even simpler:
this.gDiv.addEventListener('click', () => {
alert(this.tasks);
});
这篇关于`this.some_property` 在匿名回调函数中变为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!