What is the proper way to use _self to always have access to an object? Is using _self ok, or is it bad practice?
I want a good way to get at myObject's attributes and methods, even from functions that aren't called in myObject's context. There are solutions like .bind(this), using _self, and jQuery's $.proxy().
For example:
var myObject = {
name: 'Tyrion',
alias: 'imp',
_self: function() {
return this;
},
// I know this context is fine, but let's pretend it's being called from elsewhere.
getAlias: function() {
var _self = myObject._self();
return _self.alias;
}
}
In order to do what you're looking to do, you'd have to change a few things. @elclanrs is right about what your
thiscontext is. I'll put two options below.The other option is a bit different, and not as usable, but I'm adding it so you can see it:
in the second instance,
getAliaswould be better as a prototype method, but you won't have access to the_selfvariable, onlythis.