For example, if I have the object:
function Website(){
this.images = [];
}
Website.prototype.getImages = function(){
jQuery('img').each(function(key, val){
this.images.push(val.src);
})
}
and I try to call website.getImages() I get this error: TypeError: Cannot call method 'push' of undefined
So, in order to fix this, I would do:
Website.prototype.getImages = function(){
var images = this.images;
jQuery('img').each(function(key, val){
images.push(val.src);
})
}
But I don’t see this solution as clean, because what if im trying to access several variables.
Is there a cleaner and better way to do this?
You can do this:
In a general sense
thisis set according to how a function is called, so as soon as you nest functions you have to do something to ensurethisis set correctly for the inner function, e.g.,.call()or.apply()– or.bind(), though.bind()isn’t supported by IE until version 9.jQuery functions that take callbacks always set
thisto something logical – in most cases the particular DOM element being processed at the time. But of course that doesn’t help when you want it to be something else.