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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With