469,281 Members | 2,484 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,281 developers. It's quick & easy.

this

I've noticed some confusion about the use of the this keyword. It is set for
each invocation of a function. There are 4 basic calling patterns:

1. foo()
2. bar.foo()
3. new foo()
4. foo.apply(bar)

In the first case, foo's this will be set to the global object (aka window).
This is an acceptable behavior for global functions, although null would have
been a better choice. This is very unfortunate behavior for inner functions,
because it makes it harder to write helper functions within a method.

In this second case, foo's this will be set to the bar object. This supports
calls to methods. Unlike some other languages (like Java), the use of this
within a method must be explicit.

In the third case, foo's this will be set to a new object that is linked to
foo.prototype. This supports constructor functions. Note that constructor
function must be called with the new prefix. If the new prefix is missing,
it degenerates to the first case, and the constructor will clobber the global
object.

In the fourth case, foo's this will be bar. This makes it possible to call a
function that is not a method of the object as though it is a method of the
object.

http://www.crockford.com

Jul 20 '05 #1
1 1389
Douglas Crockford wrote:
I've noticed some confusion about the use of the this keyword. It is set for
each invocation of a function. There are 4 basic calling patterns:

1. foo()
2. bar.foo()
3. new foo()
4. foo.apply(bar)

<SNIP>

In the fourth case, foo's this will be bar. This makes it possible to call a
function that is not a method of the object as though it is a method of the
object.


Have you ever heard of this 4th case being called "environmental
acquisition"? There's a paper on it at:

http://www.ccs.neu.edu/home/lorenz/papers/oopsla96/

There was also a python and smalltalk usenet thread about it a couple of
years ago; python because apparently Zope makes use of this concept. I
mentioned Javascript does too and that was the end of the thread ;)
Jul 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by James | last post: by
5 posts views Thread by Scott D | last post: by
2 posts views Thread by Nick | last post: by
2 posts views Thread by Alexander Ross | last post: by
reply views Thread by Dan Foley | last post: by
5 posts views Thread by Lee Redeem | last post: by
5 posts views Thread by christopher vogt | last post: by
6 posts views Thread by Phil Powell | last post: by
1 post views Thread by Michel | last post: by
11 posts views Thread by Maciej Nadolski | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.