javascript对象变量在匿名函数内变为未定义 [英] javascript object variable becomes undefined inside anonymous function

查看:81
本文介绍了javascript对象变量在匿名函数内变为未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我无法弄清楚为什么变量 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代替这个(例如):

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));

无论哪种方式都可以。

编辑:感谢您的编辑建议。

Thanks for the edit suggestion.

这篇关于javascript对象变量在匿名函数内变为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆