I am asking this from a language design point of view. So I am trying to find out
- What is the rationale for the behavior of
this
?
- To what degree the behavior of
this
was a mistake, or could be improved upon?
To clarify why I'm uneasy about this
, consider this example:
var a = {};
a.f = function(){ return this; }
var f = a.f;
// f() != a.f()
Note how easily the object to which f()
belong is lost: separated from a
, this
becomes the global object (window
for browsers).
Now consider:
var newA = function(){
var self = {};
self.f = function(){ return self; }
return self;
}
var a = newA();
var f = a.f;
// f() == a.f() !
Without using this
at all, we are able to establish and maintain the object context regardless of where or how the method is used. I can't help but think that, with the power that closures provide, this
becomes superfluous, and perhaps even a little dangerous...
I'm not on some vendetta against this
, or looking to start an argument; I'm merely trying to better understand it. I do appreciate that 'this' can be useful, but recognize that it can be confusing as well... Certainly confusing to beginners, and perhaps to experts as well in sufficiently obscure cases.
And yet, it remains a heavily-used and seemingly well-respected part of the language, in a time when other core aspects of the language seem fair game for shunning (i.e., Crockford and with
or new
). What am I missing then, that makes this
indispensable?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…