如何从内部函数中找到调用者?

时间:2010-10-07 11:59:20

标签: javascript closures language-features

<input type='button' id='btn' value='click' />

<script type="text/javascript">
 var jObject = {
  bind : function(){
   var o = document.getElementById('btn');
   o.onclick = function(){
    // How can I find caller from here ?
   }
  }
 };
 jObject.bind();
</script>

更新

我从这里读了一些技巧 - http://www.mennovanslooten.nl/blog/post/62

现在我可以在内部函数中获取jObject。

<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>

1 个答案:

答案 0 :(得分:0)

onclick内,this会引用您点击的<input id="btn">元素,例如:

var jObject = {
 bind : function(){
  var o = document.getElementById('btn');
  o.onclick = function(){
   alert(this.value); //alerts 'click'
  }
 }
};
jObject.bind();