开发者

Who is calling my javascript method?

开发者 https://www.devze.com 2023-02-03 06:50 出处:网络
I\'m trying to un开发者_JAVA百科derstand what is the \"this\" referencing inside my method, the method is declared like:

I'm trying to un开发者_JAVA百科derstand what is the "this" referencing inside my method, the method is declared like:

(corrected as the answers asked for, but still not working)

Myclass = function() {
    this.focused = function() {
        alert("caller = " + this.focused.caller);
    }
}
var obj = new Myclass();

and it's showing:

this.focused is undefined

So, how can I get the caller for this function?


The way I would debug this is to add a line

console.info(this)

If you are developing with FireBug, it will show you right away what's going on. Who "this" is depends on where it is getting called from - it may be the "window" object.


You can use:

var name = arguments.callee.caller.name;


How about:

obj = new Myclass() {

    this.focused = function() {
        alert("caller = " + Function.caller.name);
    }
}


You must define your object correctly if you are going to get the result you expect.

Myclass = function() {
  this.focused=function() {
    alert("caller = " + this.focused.caller);
  };
}
obj = new Myclass();


Looks like the problem was on the event registering, with

window.onfocus = self.focused;

it was not working, but with

var self = this;
window.addEventListener("focus", function() { self.focused(); }, false);

it works well..

I just wonder why it also don't work with:

var focused = this.focused;
window.addEventListener("focus", function() { focused(); }, false);
0

精彩评论

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