Re: 'this' confusion (heading off topic)
- From: Jon Gómez <jgomez@xxxxxxxxxxxxxxx>
- Date: Thu, 19 Mar 2009 18:44:02 -0400
Thomas 'PointedEars' Lahn wrote:
On the contrary, what `this' would refer to is quite easy to determine if
you imagine the context in which it occurs to be entered. Because, as in
other programming languages supporting this mechanism, it is the caller that
determines the `this' value. And in ECMAScript implementations, where there
is no caller (or the caller is the Global Object), `this' refers to the
Global Object.
A good thing to bear in mind while programming Javascript.
Even with the explanation, it is a little disturbing to the uninitiated
as you call us that these are all different:
setInterval(obj.func, 1000)
setInterval("obj.func", 1000)
setInterval("obj.func()", 1000)
setInterval(obj.func(), 1000)
I think most of why it makes sense in Javascript for me, and it is just
my opinion, is the consistency it gives to the idea of the function as
an object assigned as a value of a property.
In a language with classes, it may be reasonable for function objects to
be tied to the object they are defined on. Not saying it has to be one
way or the other, though, just that there is a rationale in that the
function can be considered more closely linked to the object because of
the class definition.
Since you brought up the comparison of languages, I thought I'd throw in
a possible counter-example. I feel the language Ruby, in at least one
context, acts as I suggested. One can grab methods from objects using
Object.method, which remain associated with the originating object:
"Method objects are created by Object#method, and are associated with a
particular object (not just with a class). They may be used to invoke
the method within the object, and as a block associated with an
iterator." -- Programming Ruby (Hunt and Thomas)
On the other hand, there are proc objects which are not directly bound
to an originating object (but to closures...).
Jon.
.
- References:
- 'this' confusion
- From: robean
- Re: 'this' confusion
- From: Thomas 'PointedEars' Lahn
- 'this' confusion
- Prev by Date: Re: getting hidden form fields...
- Next by Date: Re: Select boxes and variable amount of rows
- Previous by thread: Re: 'this' confusion
- Next by thread: Re: 'this' confusion
- Index(es):
Relevant Pages
|