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;
}
}
thisis determined by the invocation of the function. (aka, the way the function is called) See my other answers for more details.
Instead of worrying about the context of this, a workaround is to assign this to a value in an outer function, and then access that value in an inner functions. This is called closure
FYI:
If _self returns myObject, context would not mater.