I thought I understood how javascript scope worked until now. This is what I have
function MFCommentsHandler(node, type, item) {
this.get = function(returnType){
...
}
function getButton(){
var button = document.createElement('button'),
get = this.get;
button.innerHTML = 'Load more comments';
button.onclick = function(){
console.log(get);
get('html');
}
return button;
}
}
I use inner functions to append the element generated by getButton
to the document, but when I click it I get get is not a function
. Why is get
undefined inside of the onclick
function?
this
depends only on how you call a function. It can be implicit, but in your case, you lost the context. You need to cache this
in the upper scope:
function MFCommentsHandler(node, type, item) {
var self = this;
this.get = function(returnType){
...
}
function getButton(){
self.get(); // cached reference
...
}
}
Or you can explicitly pass the context when you call getButton
:
function MFCommentsHandler(node, type, item) {
this.get = function(returnType){
...
}
function getButton(){
this.get();
...
}
getButton.call(this); // explicit context
...