I have this code:
PageList: function(url, index, classes){
this.url = url;
this.index = index;
...
};
PageList.prototype.toHTML = function(){
var div = $('<div class="container"></div>');
var p = $('<p></p>');
var link = $('<a></a>');
$.each(this.elements, function(index, array_value){
console.log(this.url);
...
}
}
And it worked as expected.
The problem was that console.log(this.url) was printing undefined, so I reworked the code to look like this:
PageList.prototype.toHTML = function(){
var div = $('<div class="container"></div>');
var p = $('<p></p>');
var link = $('<a></a>');
var instance = this;
$.each(this.elements, function(index, array_value){
console.log(instance.url);
}
}
I know that the problem was on the closure not taking this as the value of the instance, but as far as i know a reference to this inside a function that doesn’t have an instance bound to it must refer to the window object, instead of undefined, at least that’s the case on many of the browsers out there.
So what exactly is going on on my code.
Note: I’m using jQuery and this.elements is already defined.
Edit: Now im figuring out that $.each is a non-instance function, so my callback is being called from $.each but it must be window the reference to this, still thinking about it.
According to the jQuery docs for
$.each:In JavaScript, when you hand off a callback function to a higher-order function (in this case,
$.each), the higher-order function can decide what the value ofthiswill be when the callback runs. There is no way for you to control this behavior — simply don’t usethis(e.g., by using a reference likeinstancein your example or via a closure).Check out the context-setting functions
Function.callandFunction.applyto understand how a higher-order function like$.eachsets thethiscontext of a callback. Once you read those MDN pages, it might clear a few things up.Here’s a quick example:
And to use it:
My example
Array.forEachWithContextis similar toArray.forEach. However, it takes a callback and a second argument that is used as the value ofthisduring the execution each of those callbacks.