Can you help me to understand why these two JavaScript functions have different results when console.log(self)
is executed?
The first code:
var test = {
init: function() {
var self = this;
document.getElementById('show-button').addEventListener('click', self.showButton, false);
},
showButton: function() {
var self = this;
console.log(self);
}
}
test.init();
Will result the following on the console when button show is clicked:
<button type="submit" class="btn btn-default" id="show-button" title="Show the list">Show</button>
Whereas the second code:
var test = {
init: function() {
var self = this;
function show() {
self.showButton();
}
document.getElementById('show-button').addEventListener('click', show, false);
},
showButton: function() {
var self = this;
console.log(self);
}
}
test.init();
Will result the following on the console when button show is clicked:
Object {init: function, showButton: function}