代码之家  ›  专栏  ›  技术社区  ›  cryo

获取用javascript调用函数调用方的“this”

  •  3
  • cryo  · 技术社区  · 14 年前

    有可能得到 this 一个函数 caller 在javascript中用调用 没有 经过 以一种支持IE和firefox/chrome等的方式来解释这些论点?

    例如:

    var ob = {
        callme: function() {
            doSomething();
        }
    }
    ob.callme();
    
    function doSomething() {
        alert(doSomething.caller.this === ob); // how can I find the `this` that 
                                               // `callme` was called with 
                                               // (`ob` in this case) without 
                                               // passing `this` to `doSomething`?
    }
    

    我开始怀疑这不是,但我想我不妨问一下,因为这会使我的代码更短,更容易阅读。

    1 回复  |  直到 10 年前
        1
  •  3
  •   Christian C. Salvadó    14 年前

    嗯,我能想到的最接近的,没有 技术上 将值作为 论点 ,将设置 this 价值观 doSomething 功能。

    自从 剂量测定法 默认情况下,如果您像这样调用函数,则它不绑定到任何对象 doSomething(); 这个 其中的值将引用全局对象,这通常不太有用…

    例如:

    var ob = {
      callme: function () {
        doSomething.call(this); // bind the `this` value of `doSomething`
      }
    };
    
    function doSomething () {
      alert(this === ob); // use the bound `this` value
    }
    
    ob.callme();