How to best use 'this' when its unavailable
say I create someObj
like this
var someObj = function(){
var self = this;
//use this normally
document.body.addEventListener('click',function(){
//use self because this is unavailable
},false)
}
new someObj();
In the event this
is not the someObj
which id like to use but in this case the body element. Is there a best practice way to get开发者_JAVA技巧 someObj
or is declaring some self
var like in the example considered any good?
Using self
seems fine to me.
You might also want to check out using call
or apply
(see for example odetocode and specifically about this
in this post)
In my experience, declaring something like 'self' is the easiest way to do it.
I would consider your code to be perfectly acceptable.
精彩评论