OK, this may sound ultra-simple, but since it's the very first time I'm getting really serious with JavaScript/jQuery, I want to know what's the best way to go about it.
So, here's the situation:
var someClass = function()
{
var someProperty;
/*********************************
Initialisation
*********************************/
this.construct = function(options){
this.someProperty = "someValue";
$("#someDiv").click(function(){
// I want to access "this" (= the someClass object) here
});
}
}
var theObj = new someClass();
Now, here's what: Given that, in my particular case, theObj is just a single (global) object, I could obviously do :
$("#someDiv").click(function(){
console.log(theObj.someProperty);
});
But I most definitely do not like it - and there must be a more elegant/object-oriented-friendly way.
So, how would you go about it?
Since you're not using the .prototype to add methods, and are instead creating them as privileged methods within the class, just use an additional variable in the constructor's scope that refers to the object:
var someClass = function() {
var self = this;
...
};
This allows you to preserve the normal jQuery semantics that this refers to the clicked element, whilst making self available to refer to the wrapping object. For this semantic preservation reason I would specifically recommend against using .bind(this).
Regarding your final proposed "solution" of just using theObj inside the callback - you should also never refer to an object by its own name from inside itself, since those names are not under your control and may change. It might be safe in your current code, but it's a nightmare for code maintenance and code isolation.
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