How can I find caller from inner function?
<input type='button' id='btn' value='click' />
<script type="text/javascript">
var jObject = {
bind : function(){
var o = document.getElementById('btn');
o.onclick =开发者_JAVA技巧 function(){
// How can I find caller from here ?
}
}
};
jObject.bind();
</script>
UPDATE
I read some trick from here - http://www.mennovanslooten.nl/blog/post/62
And now I can get jObject inside inner function.
<input type='button' id='btn' value='click' />
<script type="text/javascript">
var jObject = {
bind : function(){
var o = document.getElementById('btn');
o.onclick = function(jObj){ // 1. add this
return function(){ // 3. wrap with return function(){ ... }
alert(jObj); // 4. now I can get jObject here.
}
}(this); // 2. and this
}
};
jObject.bind();
</script>
Inside your onclick
, this
will refer to the <input id="btn">
element you clicked, for example:
var jObject = {
bind : function(){
var o = document.getElementById('btn');
o.onclick = function(){
alert(this.value); //alerts 'click'
}
}
};
jObject.bind();
精彩评论