I am developing a JQuery plugin that stores private data in the object’s data field (as was recommended in an article I found):
$.fn.awesomify = function (schema, data) {
$(this).data('schema', schema);
}
I can then retrieve this value in a private method:
function rebuild() {
var schema = $(this).data('schema');
}
Now the problem I have is that the value of $(this) is different when the method gets called from a different object. For example, the onclick event of an href:
var a = ...;
a.click(function () {
rebuild(); // Now $(this) is the a-object
});
How should I solve this?
Thanks!
This is because the value of
thisis determined at invocation time, and is set to the object which the method belongs to, orwindowif the method is not attached to an object*;rebuild()is not attached to an object, sothisiswindow.You can either pass the value of
thisin as an argument, or use theFunction.prototype.call/Function.prototype.applymethods;or:
* -> Exception is if you’re in strict mode, where its
undefined, but this isn’t relevant here.