小编kel*_*bra的帖子

javascript对象变量在匿名函数内变为未定义

所以我无法弄清楚为什么变量this.tasks在我的目标对象内部的add事件监听器中变得未定义.我觉得它可能与异步编程有关(我仍然不完全理解).对不起,我有点像一个JS菜鸟,但是如果你们能解释一下我做错了什么,什么可能是更好的解决方案呢!谢谢.

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

    } …
Run Code Online (Sandbox Code Playgroud)

javascript anonymous-function undefined

12
推荐指数
2
解决办法
1万
查看次数

标签 统计

anonymous-function ×1

javascript ×1

undefined ×1