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);
精彩评论