Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't access variable in another function inside object literal

I have following code of javascript

var Obj = {
    init: function () {
        this.over = $('<div />').addClass('over');
        $('body').append(this.over);
        $('.click').on('click', this.show);
    },
    show: function () {
        console.log(this.over);
    }
}

Obj.init();

When this does is when user clicks a .click link then it triggers show function and logs out the dom element created in init function. But the problem is then it logs out undefined. Why? How to solve it?

like image 597
Om3ga Avatar asked Jul 07 '26 22:07

Om3ga


1 Answers

try this :

var Obj = {
init: function () {
    this.over = $('<div />').addClass('over');
    $('body').append(this.over);
    $('.click').on('click', this.show);
},

show: function () {
    // here the 'this' is the button , not the obj object ..
    console.log($('.over'));
}
}

Obj.init();

another option :

var Obj = {
init: function () {
    this.over = $('<div />').addClass('over');
    $('body').append(this.over);
    var that = this;
    $('.click').on('click', function(e){
       that.show.call(that, e); // calling the show function with call, causing 'this' to be obj
    });
},

 // 'this' is the obj
show: function (e) {
    console.log(this.over);
}
}

Obj.init();
like image 162
IdanHen Avatar answered Jul 10 '26 11:07

IdanHen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!