开发者

Why is test.elem undefined in this scenario?

开发者 https://www.devze.com 2023-03-01 11:41 出处:网络
The title gives the error I get when I use the following: var test = { elem : undefined, init : function() { console.log(\"test.init() fired\");

The title gives the error I get when I use the following:

var test = {

    elem : undefined,

    init : function() { console.log("test.init() fired");

        elem = $("#id开发者_如何学运维"); 
        console.log("elem assigned to jQuery object");

        elem.click(function() { console.log("elem clicked"); });
        console.log("elem click handler created");

    }

};

test.init();
test.elem.click();

I don't understand. If I run test.init() where it assigns the value for test.elem, why would it be undefined when I try to access it later?


You're creating a new reference called 'elem' inside of the init function rather than referencing test.elem.

Inside init you need to assign the element to 'this.elem', so it would read:

init : function() {
    console.log("test.init() fired");

    this.elem = $("#id"); 

    console.log("elem assigned to jQuery object");

    this.elem.click(function() {
        console.log("elem clicked");
    });

    console.log("elem click handler created");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消