I have the following Javascript,
eventManager: {
$musicGenres : null, // $musicGenres is the selector for a div-container of inputs
musicGenres : [],
// Functions
handle : function(selectors) {
selectors = (typeof selectors === 'undefined') ? {
'musicGenres' : '#musicGenres'
} : selectors; // selectors default values...
this.$musicGenres = $(selectors['musicGenres']);
console.log("CHANGED $musicGenres TO " + this.$musicGenres);
this.$musicGenres.find('input').change(this.reloadMusicGenres);
},
reloadMusicGenres : function() {
console.log("IN FUNCTION $musicGenres IS " + this.$musicGenres);
},
, call the function eventManager.handle() on my page and trigger the change-Event of one of those inputs, which outputs
CHANGED $musicGenres TO [object Object]
IN FUNCTION $musicGenres IS undefined
what I don't understand. I've set $musicGenres to a new value, but in the reloadMusicGenres-function it stays undefined. Even when I manually access $musicGenres' value through the console by typing in eventManager.$musicGenres it outputs the right value.
Could anybody help me? That really worries me.
The
contextofthishas changed. The easiest way to address the issue is to referencethisoutside the function, or pass adataobject (as suggested by the two other fine posters, Richard Healy and AlliterativeAlice).A third way is to explicity
bindthe context ofthis. Using jQuery, you can achieve this by calling$.proxy. So, this:becomes:
$.proxywill return a new function, wherethiswill always be bound toeventManager. If you're interested in moving away from jQuery,Function.prototype.bindis your answer (Edit: an example of which is provided by Zoltan's answer)Here's some links for documentation on how to use these fine functions:
jQuery proxy: https://api.jquery.com/jQuery.proxy/
Bind function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind