I have a Problem accessing an Object function using "this". In case of the below example (which is simplified, because I cannot supply actual code due to various reasons) the function call this._getEntry() is "undefined" when calling createList().
I would hope for some opinions on wether this is due to a misunderstanding of javascript closures or rather a syntax error.
In the latter case I will have to find the error in the actual code myself.
If it is a misunderstanding of javascript or dojo concepts I would really appreciate some help on how to correctly scope and access the below mentioned function (_getEntry()).
var OBJECT = {
_getEntry : function(entry){
var li = document.createElement('LI');
li.appendChild(document.createTextNode(entry));
return li;
},
createList : function(entryArray){
var list = document.createElement('UL');
dojo.forEach(entryArray,function(entry){
list.appendChild(this._getEntry(entry));
});
dojo.body().appendChild(list);
}
};
OBJECT.createList(["entry1","entry2"]);
thanks!
Firstly, I think your pasted code is missing ); to complete the forEach.
Secondly, forEach takes an optional third parameter which determines the context in which the passed function runs. If not given, it defaults to the global scope, so yes this is your problem. Assuming this already refers to what you need it to immediately outside the forEach, you should be able to just pass this in as the third argument to forEach and it should work, e.g.:
dojo.forEach(entryArray, function(entry){
list.appendChild(this._getEntry(entry));
}, this);
For more information: http://dojotoolkit.org/api/dojo/forEach - which is based on the API in JS 1.6 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
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