开发者

getting the "this" that a function's caller was called with in JavaScript

开发者 https://www.devze.com 2023-01-01 20:35 出处:网络
Is it possible to get the this that a function\'s caller was called with in JavaScript without passing this to the arguments in a way which supports IE as well as Firefox/Chrome et al?

Is it possible to get the this that a function's caller was called with in JavaScript without passing this to the arguments in a way which supports IE as well as Firefox/Chrome et al?

For example:

var ob = {
    callme: fu开发者_如何转开发nction() {
        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`?
}

I'm starting to suspect it's not, but I thought I may as well ask as it'd make my code much shorter and easier to read.


Well, the closest I can think, without technically passing the value as an argument, would be to set the this value of the doSomething function.

Since the doSomething function is not bound to any object, by default, if you call it like doSomething(); the this value inside it will refer to the Global object, and that's normally not too useful...

For example:

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消