Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Using setInterval inside an object

1,192 views
Skip to first unread message

Daniel

unread,
Jun 30, 2003, 9:59:48 AM6/30/03
to
Hello =)

I have an object which contains a method that should execute every x ms. I
can use setInterval inside the object construct like this -

self.setInterval('ObjectName.methodName()', this.pinginterval);

- but is there no way to do this without using the literal ObjectName? If I
write 'this.methodName()' I get "Line 1 Char 1: Object doesn't support this
property or method." in IE, and nothing happens in Firebird.

Thank you,
Daniel

Martin Honnen

unread,
Jun 30, 2003, 10:09:24 AM6/30/03
to

You would need to store the object somehow in a variable that is
accessible from the code passed to setInterval
For example when you create objects store them in an Array
function AClass () {
this.id = AClass.instances.length;
AClass.instances[this.id] = this;
}
AClass.instances = new Array()
Then in your method you script
setInterval('AClass.instances[' + this.id + '].methodName();', delay)

--

Martin Honnen
http://JavaScript.FAQTs.com/

Lasse Reichstein Nielsen

unread,
Jun 30, 2003, 10:13:43 AM6/30/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> writes:

Because the "this" keyword at the time of running doesn't refer to the
object. That is one reason to be weary about passing around code as
strings. Passing it around as a function value keeps the textual scope,
so the identifiers in the function refer to the ones that existed where
the function was written, not where it is executed.

I would write

var myself = this;
function callMethod() {
myself.methodName();
}
setInterval(callMethod, this.pinginterval)

That way you don't rely on any literals being the same when the code
is executed, but rely on the normal scope rules to keep the *value* of
myself in the function's scope chain.

/L
--
Lasse Reichstein Nielsen - l...@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'

Daniel

unread,
Jun 30, 2003, 10:20:47 AM6/30/03
to
> Because the "this" keyword at the time of running doesn't refer to the
> object. That is one reason to be weary about passing around code as
> strings. Passing it around as a function value keeps the textual scope,
> so the identifiers in the function refer to the ones that existed where
> the function was written, not where it is executed.
>

That's what I was thinking, but the alternative (as I could see it ;) would
cause my method to execute once (at object construction), and the return
value of its execution be the interval'ed object...

> I would write
>
> var myself = this;
> function callMethod() {
> myself.methodName();
> }
> setInterval(callMethod, this.pinginterval)
>

...but then you give me this workaround and a big smile on my face =). Thank
you, Lasse! Just what I was looking for!

Daniel


PS: Er vi egentlig ikke landsmænd?


Daniel

unread,
Jun 30, 2003, 10:29:12 AM6/30/03
to
> You would need to store the object somehow in a variable that is
> accessible from the code passed to setInterval
> For example when you create objects store them in an Array
> function AClass () {
> this.id = AClass.instances.length;
> AClass.instances[this.id] = this;
> }
> AClass.instances = new Array()
> Then in your method you script
> setInterval('AClass.instances[' + this.id + '].methodName();', delay)

I thought of this. Actually, I think you're responsible for me thinking
this, as I think you were the one who gave me a similar approach when I
asked about how to determine an object's run-time assigned name without
having to store it oneself =)
I'm gonna go with Lasse's solution, though (no offense ;), since that
requires no manual tracking of object names.

But thank you for your post =)

Daniel


Lasse Reichstein Nielsen

unread,
Jun 30, 2003, 10:50:16 AM6/30/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> writes:

> PS: Er vi egentlig ikke landsmænd?

Jo, det er vi da :)
(and I would have answered in Danish if you had asked in the Danish
group <URL:news:dk.edb.internet.webdesign.clientside> :) )

Daniel

unread,
Jun 30, 2003, 10:52:25 AM6/30/03
to
> (and I would have answered in Danish if you had asked in the Danish
> group <URL:news:dk.edb.internet.webdesign.clientside> :) )

Hæhæ! Nice =)

I didn't even know that group existed! But I'm subscribed now ;)


Daniel

unread,
Jun 30, 2003, 11:14:55 AM6/30/03
to
> var myself = this;
> function callMethod() {
> myself.methodName();
> }
> setInterval(callMethod, this.pinginterval)

Okay, it turns out I was just confusing myself and you here, because if I
just use setInterval on the function directly it works just fine, that is
when I don't screw up my syntax and write it like you did, Lasse:

function myObject() {
var o = this;
o.intervalcheck = function() { // blahblah }
self.setInterval(o.intervalcheck, 2000);
}

I had remembered (falsely, obviously ;) from reading in my Javascript Bible
(I think I need to read some more) that if the function wasn't specified as
a literal, i.e. 'o.intervalcheck()', it would just be executed at
construction time and evaluated, and the return value would be what was
"executed" at the given interval. But that only applies if you write it with
the two parentheses that cause it to execute, which of course is not the
same as assigning a function _reference_ to a variables. Sometimes I'm just
a little quick to become puzzled at why something doesn't work... So this
post is pretty much just to say sorry for wasting your time :)

And thank you =)

Daniel


Lasse Reichstein Nielsen

unread,
Jun 30, 2003, 12:18:50 PM6/30/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> writes:

> function myObject() {
> var o = this;
> o.intervalcheck = function() { // blahblah }
> self.setInterval(o.intervalcheck, 2000);
> }

This looks slightly misleading. It is equivalent to:

function myObject() {
var o = this;

var f = function() { // blahblah };
o.intervalcheck = f; // seems unused otherwise
self.setInterval(f, 2000);
}

Functions have several roles in Javascript. They act both as first
class values (which is what we use when passing a function reference
to setInterval) and as methods of objects (which is what we do when we
invoke them as "object.method()"). However, these two roles are not
compatible.

When you write "o.intervalcheck", what you get is the reference to the
function. There is nothing in this reference that can tell that the
function has been a method of the "o" object. Calling the function later
will not make the "this" keyword point to the "o" object.

If the "//blahblah" uses "this", then it is probably a mistake. If it uses
"o", then it probably works. In either case, there doesn't seem to be any
reason for making the function a property of the object.

(Incidentally, because I just read a book about it, the concept of
passing an object method as a first class value has been incorporated
into the C# language. It is called a "delegate", and it works like a
function while retaining the binding of the "this" keyword. They do
have an easier time than javascript, since functions aren't first
class values otherwise.)

rh

unread,
Jul 1, 2003, 12:17:19 AM7/1/03
to
Lasse Reichstein Nielsen <l...@hotpop.com> wrote in message news:<y8zjv8...@hotpop.com>...

> "Daniel" <sorry-n...@i-get-virus-and-spam.com> writes:
>
> > function myObject() {
> > var o = this;
> > o.intervalcheck = function() { // blahblah }
> > self.setInterval(o.intervalcheck, 2000);
> > }
>
> This looks slightly misleading. It is equivalent to:
>
> function myObject() {
> var o = this;
> var f = function() { // blahblah };
> o.intervalcheck = f; // seems unused otherwise
> self.setInterval(f, 2000);
> }
>

The two may be functionally equivalent, but the original is preferable
if a public function is desired. On the other hand a private function
may be more appropriate, in which case the "o.intervalcheck = f"
(which provides a public reference to the private function) should be
removed.

<snip>

> When you write "o.intervalcheck", what you get is the reference to the
> function. There is nothing in this reference that can tell that the
> function has been a method of the "o" object. Calling the function later
> will not make the "this" keyword point to the "o" object.
>

Agreed there's nothing perhaps in the reference that designates the
object, but there is something in the de-reference. Otherwise,
closures in Javascript wouldn't exist.

It's been noted elsewhere that it seems to be a deficiency in
Javascript that "this" doesn't refer to the object upon entry to a
closure. Nonetheless, both private and public properties of the object
are accessible within the closure. As is the object itself, provided a
reference to the object has been preserved during object construction
(e.g., var o = this).

> If the "//blahblah" uses "this", then it is probably a mistake. If it uses
> "o", then it probably works. In either case, there doesn't seem to be any
> reason for making the function a property of the object.
>

If it uses "o", then it should do better than "probably works" :-).
It's reasonable to make the function a property of the object if
closure is one of the desired effects.

//rh

Daniel

unread,
Jul 1, 2003, 4:06:33 AM7/1/03
to
> When you write "o.intervalcheck", what you get is the reference to the
> function. There is nothing in this reference that can tell that the
> function has been a method of the "o" object. Calling the function later
> will not make the "this" keyword point to the "o" object.

I'm a bit confused here as to what you mean... When I've stored the
reference to "this" in "o", is writing "o" then not equivalent to writing
"this" in regards to how Javascript interprets the code? So that writing
"o.intervalcheck" is effectively the same as "this.intervalcheck" in every
sense but the semantics?

> If the "//blahblah" uses "this", then it is probably a mistake. If it uses
> "o", then it probably works. In either case, there doesn't seem to be any
> reason for making the function a property of the object.

The //blahblah doesn't use "this". Actually, this whole thing about handling
scope in Javascript which is rather different, I think, to Actionscript
which I'm more accustomed to, made me wonder if using "this" inside a method
of the object would be understood by Javascript as a reference to the method
and not its object parent. So, assigning the object's "this" to "o"
comforted me, because I could then stop worrying about what "this" would
actually be referring to ;) Is this bad programatical style? Won't "o" be
available to every method under the object?

> (Incidentally, because I just read a book about it, the concept of
> passing an object method as a first class value has been incorporated
> into the C# language. It is called a "delegate", and it works like a
> function while retaining the binding of the "this" keyword. They do
> have an easier time than javascript, since functions aren't first
> class values otherwise.)

Good to know. I was reading up on first-class values, and read about C's
functions not being first-class values; I was wondering if that applied to
C++/C# as well (gonna be doing some of that soon, as I'm starting the
datamatiker education August 1st ;).

Thanks,
Daniel =)


--
There are 10 kinds of people: Those who know binary and those who don't.


Daniel

unread,
Jul 1, 2003, 4:26:26 AM7/1/03
to
> The two may be functionally equivalent, but the original is preferable
> if a public function is desired. On the other hand a private function
> may be more appropriate, in which case the "o.intervalcheck = f"
> (which provides a public reference to the private function) should be
> removed.

Okay, I think I'm getting what this is about! =) I didn't even think about
public and private in Javascript (I continue to underestimate what
Javascript can do, it's been a long walk from "Bah, that's just a simple
scripting language, can't take more than a couple of weeks to master" to
here, and the walk continues... ;)

> If it uses "o", then it should do better than "probably works" :-).
> It's reasonable to make the function a property of the object if
> closure is one of the desired effects.

While closure wasn't something I intentionally aimed for, I don't see any
problems with it. The object is intended as an autonomous slave horse,
providing an abstraction layer between Javascript and PHP/MySQL. It is given
orders to get/update/delete data and return objects and/or statuses. The
intervalcheck function is supposed to do periodical keepalive stuff like
pinging the database, error-checking, and maintaining a queue of waiting
commands. It's not needed as a public method, like "object.intervalcheck()",
and as I understand, the way I've programmed it here, that won't be possible
anyway?

> It's been noted elsewhere that it seems to be a deficiency in
> Javascript that "this" doesn't refer to the object upon entry to a
> closure. Nonetheless, both private and public properties of the object
> are accessible within the closure. As is the object itself, provided a
> reference to the object has been preserved during object construction
> (e.g., var o = this).

This may be a lot to ask, but could you possibly explain this bit to me? Or
if you had a link that would be nice? This "entry to a closure" concept is
new to me...

I'll be reading up on objects in the Bible ;)

Thanks for your help, RH! =)

Daniel

Daniel

unread,
Jul 1, 2003, 4:51:24 AM7/1/03
to
Now wait... I think I'm getting confused again... If my o.intervalcheck
function is private, then that would render it useless as a method, right?
So how can it still be executed by setInterval which is initiated in the
document? Is it because setInterval is initiated in the process of
constructing a given object, and a public reference is created by executing
the setInterval method to ensure accessibility, after which this reference
is used in the document, and not really "ObjectName.intervalcheck" as one
(at least I) would think?

Sorry for posting this after the other post, but it just struck me.

Daniel


Richard Cornford

unread,
Jul 1, 2003, 6:32:35 AM7/1/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> wrote in message
news:3f0145b5$0$97265$edfa...@dread12.news.tele.dk...
<snip>

>While closure wasn't something I intentionally aimed for,
>I don't see any problems with it. ...
<snip>

Closures are wonderful things and make JavaScript capable of doing
unusual and unexpected things but they are not totally without problems.

The first problem only effects IE and is more related to DOM interaction
and ActiveX than to pure JavaScript objects. It appears that if a DOM
Element or ActiveX object holds a reference to a JavaScript object (as
and expando property or event handling function reference) while that
object holds a reference to that DOM Element or ActiveX object then IE
will not garbage collect either even when navigating away from the page.
Scripts that form such circular reference effectively tie up ever
increasing amounts of memory until IE is closed.

The circular references can be more indirect, involving multiple
objects, but so long as they are circular and include a DOM element
(which includes the document object[1]) or an ActiveX object the problem
exists.

Closures, like all else in JavaScript are objects. At least they imply
the persistence of objects. Specifically, for the inner function of a
function to continue to have access to the local variables and
parameters of its outer function the 'variable' object from the
execution context of the outer function's invocation must continue to
exist. Closures risk forming circular references when, for example,
assigning an inner function to an event handling property of a DOM
element if the reference to the DOM element is held in a local variable
or an outer function parameter as these references will be preserved on
the variable object and the inner function object must have a reference
to that variable object (however indirect) in order to be able to refer
to the variables and parameters of its outer function.

Being aware of the problem, it is possible to limit the size and
contents of closures, null local variables that refer to DOM elements if
they are no longer needed and ultimately institute some sort of cleanup
to break any unavoidable circular references onunload.

The second problem with closures is that the inner functions are
function objects. Function objects need to be created (which has an
overhead) and consume memory. ECMA script allows implementations to
optimise the creation of function objects by "joining" function objects
that would be "indistinguishable". That optimisation is optional and
recent experiments have suggested that only Gecko browsers implement any
function joining and they do not currently do so for inner functions at
all. There is no evidence that IE or Opera do any joining at all.

The result is that a new function object will be created for each inner
function for each invocation of its outer function.

Consider:-

function MyObject(x){
this.x = x;
this.method = function(){
return this.x;
};
}

- as opposed to:-

function MyObject(x){
this.x = x;
}
MyObject.prototype.method = function(){
return this.x;
}

The first creates a new function object to assign to - this.method -
whenever an instance of - MyObject - is created. The second shares one
function object assigned as a property of the prototype between all
instances of - MyObject - so it must create objects instances faster and
consume less memory in the process.

The - method - method in the first example does fall into the category
of object methods that Douglas Crockford ( http://www.crockford.com )
has categorised as 'privileged', in that, if the closure formed by
this - MyObject - constructor had created private instance members then
the - method - method would be able to access those members. In the
example above there are no private members of the - MyObject - object
and the - method - method gains nothing by being "privileged".

My point being that the use of inner functions carries an overhead and
that makes me think that it would be best to restrict their use to
instances where the fact that they are inner functions, and thus in a
position to form and _exploit_ the resulting closures, has a manifest
advantage.

Lasse thinks that authoring convenience and ease of maintenance argue
against worrying about this aspect of inner functions to any significant
degree. I am a bit more obsessed with maximising performance. No one
else has expressed an opinion. Knowing the situation you can make up
your own mind about.

Richard.

[1] I surmise that IE's circular reference problem might apply to any
object implementing the W3C Node or Element interfaces as that includes
DOM elements and the document, but I have not yet had a chance to
experiment to find out if the problem can be nailed down to a particular
DOM interface implementation.


Lasse Reichstein Nielsen

unread,
Jul 1, 2003, 7:32:57 AM7/1/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> writes:

> I'm a bit confused here as to what you mean... When I've stored the
> reference to "this" in "o", is writing "o" then not equivalent to writing
> "this" in regards to how Javascript interprets the code?

Yes, in the current scope, but not necessarily inside other functions
that are defined in this scope.

The "this" keyword is a keyword, not an identifier. The "this" keyword
is set when you call a function as a method ("o.method()") but not when
you call a function reference directly ("var foo=o.method;foo()"). In the
latter case, the "this" keyword refers to the global object during the
execution of the body of "foo". The value of the "this" keyword depends
on how the function was called.

The scope of identifiers is textual, so when you write

function foo () {
var o = ...;
function bar() {... o ...}
...
}

then the "o" inside the "bar" function refers to the declaration
outside, because it is the closest textually enclosing declaration.
The "o" is declared for the entire function body of "foo". The "bar"
function is textually inside this body, so it is the scope of that
particualr declaration of "o". (Since "o" is a local variable, each
call to "foo" has its own, and each call to "foo" creates a new "bar")

If a "bar" function is passed around, the value leaving the scope
where it was declared, it will keep referring to the same local
variable of the particular call to the "foo" function where it was
created. That is the point of a closure.

> So that writing "o.intervalcheck" is effectively the same as
> "this.intervalcheck" in every sense but the semantics?

Here it is. Inside the function itself, it might be, depending on
how it is called.



> made me wonder if using "this" inside a method of the object would
> be understood by Javascript as a reference to the method and not its
> object parent.

It depends. If called as a method, "this" refers to the object for
which the function is a method. If called as a function reference,
"this" refers to the global object (which is stupid design, but that's
a different story).

> So, assigning the object's "this" to "o" comforted me, because I
> could then stop worrying about what "this" would actually be
> referring to ;) Is this bad programatical style? Won't "o" be
> available to every method under the object?

It is not bad style to assign the value of "this" to a local variable
to be able to capture it in closures. It is a well known way of doing
exactly that.

> Good to know. I was reading up on first-class values, and read about C's
> functions not being first-class values; I was wondering if that applied to
> C++/C# as well

For C, it is a matter of definition. Since C only has one scope, the
global one, and functions cannot be nested, there is no need for
closures. You *can* pass function /pointers/ as first class values (as
any pointer). In practice, I can't see a difference between that and
passing the function itself (except that it allows you to mess with
pointer arithmetic and shoot yourself in the foot ... and that it makes
writing code that exploits buffer-overflows much easier).

> (gonna be doing some of that soon, as I'm starting the
> datamatiker education August 1st ;).

Congratulatons :)

Daniel

unread,
Jul 1, 2003, 7:31:12 AM7/1/03
to
> My point being that the use of inner functions carries an overhead and
> that makes me think that it would be best to restrict their use to
> instances where the fact that they are inner functions, and thus in a
> position to form and _exploit_ the resulting closures, has a manifest
> advantage.
>
> Lasse thinks that authoring convenience and ease of maintenance argue
> against worrying about this aspect of inner functions to any significant
> degree. I am a bit more obsessed with maximising performance. No one
> else has expressed an opinion. Knowing the situation you can make up
> your own mind about.

In this particular scenario, I will at any time have just one instance of
this object in a given document. So regarding the question of inner vs.
outer functions, the overhead by using inner functions would only be
theoretical, and for some reason I favour nesting code specific to just one
object inside the object. Not so much because of programatical reasons, but
more because I guess it "fits" better with the way my head understands it
(at least for the moment being ;)

As for the potential problem with circular references you describe, I'll
definitely have to take this into account. Your post was very informative,
and I probably wouldn't have realized this issue existed had it not been for
you, so thank you _very_ much for taking the time to write such an in-depth
reply! =)

Regards,

Daniel

unread,
Jul 1, 2003, 8:00:07 AM7/1/03
to

"Lasse Reichstein Nielsen" <l...@hotpop.com> wrote in message
news:8yriv5...@hotpop.com...

> It depends. If called as a method, "this" refers to the object for
> which the function is a method. If called as a function reference,
> "this" refers to the global object (which is stupid design, but that's
> a different story).

I definitely agree =) The way the "this" keyword is used in Javascript has
caused me quite a lot of confusion, it doesn't always make sense the way
it's used - sometimes it seems like things have been "patched up" to do some
kind of workaround that doesn't make programatical sense. Like when you
reference a form from within an element in the form using "this.form" - that
doesn't make sense, since that *should* indicate a form nested in the
element. I haven't seen the ECMA specs, but in Actionscript the equivalent
reference would have been "this._parent" which makes much more sense, both
logical and programatical (plus, it makes no assumption about what type of
object the parent is).

> It is not bad style to assign the value of "this" to a local variable
> to be able to capture it in closures. It is a well known way of doing
> exactly that.

Great =)

> Congratulatons :)

Actually, anyone with a B level in math and a highschool diploma gets in,
so... But thanks! =) Hehe ;)

Thanks to you, RH, and Richard, I'm beginning to get a really good
understanding of this. You guys rock! The time and effort you're spending
here really means a lot to me (and others!) =)

Thanks,
Daniel

PS: Jeg har kigget lidt på din side - den der random art-dippedut er helt
vildt cool =)

Lasse Reichstein Nielsen

unread,
Jul 1, 2003, 8:18:48 AM7/1/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> writes:

> Like when you reference a form from within an element in the form
> using "this.form" - that doesn't make sense, since that *should*
> indicate a form nested in the element.

It does make some sense. Each form element has a reference to the form
it is inside. The "onclick" handler is a function and a method of the
element (or rather the DOM node corresponding to it) that it is on, so
when it is called, they "this" keyword points to the form element.

> I haven't seen the ECMA specs, but in Actionscript the equivalent
> reference would have been "this._parent" which makes much more sense, both
> logical and programatical (plus, it makes no assumption about what type of
> object the parent is).

ECMA only specifies the language, not the runtime environment (since
that can differ depending on the application - javascript is used in
more than just browsers). In browsers, the runtime environment is the
Document Object Model (DOM) specified by the W3C.

The corresponding parent notation is "this.parentNode", which refers
to the parent in the DOM tree structure (which is not necessarily the
form element). You can crawl the tree using ".firstChild",
".nextSibling", etc.

I guess the people who first created the (pre-specification) DOM often
needed to refer to other elements of the same form, so the easiest was
to put a reference to the form where it was easily accessible: on each
element. I'll have to agree that it was a good choice.

> PS: Jeg har kigget lidt på din side - den der random art-dippedut er helt
> vildt cool =)

Takker :)

Daniel

unread,
Jul 1, 2003, 9:03:17 AM7/1/03
to

"Lasse Reichstein Nielsen" <l...@hotpop.com> wrote in message
news:k7b2tp...@hotpop.com...

> It does make some sense. Each form element has a reference to the form
> it is inside. The "onclick" handler is a function and a method of the
> element (or rather the DOM node corresponding to it) that it is on, so
> when it is called, they "this" keyword points to the form element.

OOOHH!!! It's just the way I've been reading it! I've read it as, literally,
a part of a path, when really the ".form" is a property of the object
referenced by "this" (an object, which in turn can be extended with
"paths" - properties - to address another object). ".form" could just as
well contain a reference the top document, giving us a whole different
scenario. And "_parent" in Actionscript is just a property as well. A path
is really nothing but a series of objects linked together, and that linkage
can be arbitrary, not necessarily hierarchical. Come to think of it, the
concept of hierarchy itself is a perception... I think I just had a small
wake-up call :P

Thanks! =)

Daniel

Richard Cornford

unread,
Jul 1, 2003, 9:40:35 AM7/1/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> wrote in message
news:3f017100$0$97169$edfa...@dread12.news.tele.dk...
<snip>
>... , and for some reason I favour nesting code specific to just

>one object inside the object. Not so much because of programatical
>reasons, but more because I guess it "fits" better with the way my
>head understands it (at least for the moment being ;)

There are many patterns for creating JavaScript object classes, looking
around Douglas Crockford's site (and following some of the links from
there) will expose several approaches.

I like the idea of grouping all code related to an object into one
structure in a way similar to Java. It is still feasible to do that with
JavaScript without creating a unique function object for each method of
each object instance.

The following executes a function expression as the file loads, that
function call returns a function that will act as a class constructor.
The resulting closure acts as a repository for private static members
but it can also server to group the code for the entire class into one
function body. However, because this constructor returning function is
only called once any inner functions assigned to the prototype of the
constructor will be shared by all instances of the class and that gives
you the clear object code structure while not creating more function
objects than is needed.


var MyObject = function(){
var counter = 0; //private static (class) member

function incrementCounter(){ //private static (class) method.
return counter++;
};

function constructor(id){ //class constructor.
this.id = id;
var self = this;

//call private static (class) method and assign the returned
//index to a private instance member.
var index = incrementCounter();

this.getIndex = function(){ //privileged instance method.
return index;
};
};

//privileged static (class) method (a property of the constructor)
constructor.getNoOfInsts = function(){
return counter;
};

//public instance method that is also privileged at the class
//level. It has no access to the closure formed when
//constructing new objects. The one function object is
//shared by all instances of the class as it has been assigned
//to the prototype of the constructor function.
constructor.prototype.getId = function(){
return this.id;
}

return constructor; //return the constructor.
}(); //simultaneously define and call (one-off)!

var test = new MyObject('anyId');

There is no need, but it also remains possible to extend the prototype
after the constructor has been returned from the one-off function
call.:-

MyObject.pubStatic = "anything" //public static (class) member

MyObject.prototype.pubInstVar = 8; //public instance member

Richard.

--

Example JavaScript DOM listings for: Opera 7.11,
Mozilla 1.2 and ICEbrowser 5.4
<URL: http://www.litotes.demon.co.uk/dom_root.html >


Daniel

unread,
Jul 1, 2003, 10:32:27 AM7/1/03
to

"Richard Cornford" <Ric...@litotes.demon.co.uk> wrote in message
news:bds30l$kqs$1$830f...@news.demon.co.uk...

> There are many patterns for creating JavaScript object classes, looking
> around Douglas Crockford's site (and following some of the links from
> there) will expose several approaches.

I've been surfing his site after you gave me the link, seems like a clever
guy (I gave him a silent J, although it's a Sweden village called "Rjukan",
so he might not want it ;)

> var MyObject = function(){
...


> }(); //simultaneously define and call (one-off)!
>
> var test = new MyObject('anyId');

This is really a brainteaser for me... I partially understand the one-off
concept here in that I can see how the "space" MyObject owns[*] in the
variable declaration becomes an object constructor that is immediately
fired, and then assigns "test" an instance of that object (which as I
understand it, isn't really a "MyObject" instance, but rather a
"constructor" instance...

[*] This is my brain's way of expressing how expressions evaluate to
something else, like "now = theCurrentTime()" >>> theCurrentTime()'s "space"
in that expression is replaced with whatever's returned by the function. I
know it would be sufficient to just say "evaluate", but since I don't
understand this, I thought it would be a good idea to try to explain how my
failing brain understands this term ;)

What exactly the MyObject function then is, I don't quite understand. As it
is not itself instantiated, it can't see it anywhere existing as an object,
actually I can't see how the counter inside will keep its value from one
object construction to another, since it - in itself - is just a function?
And why is it only called once? As I see it it will be called every time you
do a "new MyObject()"... Ofcourse it must be because I don't fully
understand objects (or functions) in Javascript but the Bible's explanations
are REALLY tame. (OT, I think I need to buy a better book - any
suggestions?)

Or is the answer in the "new MyObject('anyId')" assignment?

As I understand your code, it's a function that, when executed, returns an
object constructer that is also executed, all the while keeping track of a
counter (in a way I don't understand).

Argh, I know it must be like dancing with an elephant to help me here, so
I'll definitely understand if you just tell me to go read a book ;)

In either case, thank you for your help, Richard!

Daniel

PS: In case of the "read a book" reply, which one should I get?

Daniel

unread,
Jul 1, 2003, 10:58:45 AM7/1/03
to

"Daniel" <sorry-n...@i-get-virus-and-spam.com> wrote in message
news:3f019b7d$0$97230$edfa...@dread12.news.tele.dk...

> PS: In case of the "read a book" reply, which one should I get?

I'm gonna order the Javascript Definitive Guide as Douglas suggests on
Amazon, so that's that question answered ;)


Richard Cornford

unread,
Jul 1, 2003, 8:18:33 PM7/1/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> wrote in message
news:3f019b7d$0$97230$edfa...@dread12.news.tele.dk...
<snip>

>> var MyObject = function(){
> ...
>> }(); //simultaneously define and call (one-off)!
>>
>> var test = new MyObject('anyId');
>
>This is really a brainteaser for me... I partially understand the
>one-off concept here in that I can see how the "space"
>MyObject owns[*] in the variable declaration becomes an
>object constructor

The constructor (the inner function with the identifier "constructor")
is returned by the in-line execution of its outer function and a
reference to that inner function is assigned to the MyObject variable.
Thus the MyObject global variable becomes a reference to a function that
is an inner function of the closure formed by executing its outer
function in-line once, but that function can be used as a constructor
(that is actually true of all functions, though most of the time using a
random function as an object constructor would be pointless) and it has
already had an instance method assigned to its prototype.

The primary purpose of the inline execution of the outer function is to
provide a closure to contain private static (class) members. Variables
and functions local to the closure but also available to any other
function defined within the same closure. Which includes the constructor
and the closure formed when new objects of the class are created, their
privileged and private methods and their non-privileged public members.
However, the function expression that is executed in-line also serves as
an enclosing structure for the entire class definition. Resulting in a
more Java-like class definition.

>that is immediately fired, and then assigns "test" an instance of that
>object (which as I understand it, isn't really a "MyObject" instance,
>but rather a "constructor" instance...

" A rose by any other name . ". If you execute - var myArray = Array; -
and then call - new myArray(); - the constructor called is the Array
function object. myArray only holds a reference to that function object,
but the global Array property also only holds a reference to that
function object. A genuine working Array object is the end result.

It is a MyObject instance because - if(test instanceof MyObject) - will
compare the reference to the function object that constructed - test -
with the with the function object referred to by the global MyObject
property. The identifier "constructor" is out of scope outside the
closure formed by executing its outer function in-line.

> [*] This is my brain's way of expressing how expressions evaluate to
> something else, like "now = theCurrentTime()" >>> theCurrentTime()'s
"space"
> in that expression is replaced with whatever's returned by the
function. I
> know it would be sufficient to just say "evaluate", but since I don't
> understand this, I thought it would be a good idea to try to explain
how my
> failing brain understands this term ;)
>
> What exactly the MyObject function then is, I don't quite understand.

It is a mechanism to form a closure with the constructor function of a
class.

>As it is not itself instantiated,
>it can't see it anywhere existing as an object,

The closure formed when its inner function is returned implies the
preservation of at least the "variable" object from the execution
context of the outer function but the whole process is anonymous and
externally inaccessible (else how could the variables and function
definitions within the closure that represent private static members be
private?).

> actually I can't see how the counter inside will keep its value
>from one object construction to another, since it - in itself - is
>just a function?

The outer function is executed once and once only. The function -
function incrementCounter(){ - is an inner function of that outer
function, as is the - constructor - function, they have equal status.
Object instances are constructed by a call to the - constructor -
function, via the reference to it that was returned by the in-line
execution of the outer function and assigned to the MyObject variable.
The execution of one inner function does not impact upon the existence
of another inner function within the same closure ( well it could, but
in this case (and most cases) it doesn't).

> And why is it only called once?

Because a class only needs one constructor function object and only one
closure to act as a repository for its private static members.

>As I see it it will be called every time you
> do a "new MyObject()"...

The outer function is not called, it can never be called again because
there are not references to it left outside of the closure that was
formed when it was executed once. The outer function returned a
reference to its inner 'constructor' function and it is that function
that is invoked each time - new MyObject(); - is called.

>Ofcourse it must be because I don't fully understand objects
>(or functions) in Javascript but the Bible's explanations are
>REALLY tame. (OT, I think I need to buy a better book - any
> suggestions?)

JavaScript books are always a problem, many are out of date and most are
primarily concerned with scripting the browser DOM and don't go into the
more esoteric aspects of functions, closures or objects.

When I was first learning JavaScript "Javascript the Definitive Guide"
(then it its second edition) was the most useful book I had, but for its
DOM reference rather than its language coverage (which is still much
better than the other JavaScript books I have seen).

You will be lucky to find any reference to Douglas Crockford's
application of closures to provide JavaScript objects with private
instance members, or my application of his technique at the constructor
level to provide JavaScript classes with private static members. I even
have JavaScript books that assert that JavaScript objects cannot have
private members (of any type).

Incidentally, avoid books about JavaScritp 2. The next revision of the
ECMA Script language has not been finalised yet so anything about
JavaScript 2 is speculation based on proposals and one or two reference
implementations. It won't be practical for client-side use for at least
4 years anyway.

> Or is the answer in the "new MyObject('anyId')" assignment?

No, that is the totally standard construction of a JavaScript object.

> As I understand your code, it's a function that, when executed,
>returns an object constructer that is also executed, all the while
>keeping track of a counter (in a way I don't understand).

That "is also executed" worries me. The constructor that is returned is
only executed when - new MyObject() - is used. In my code the function
that is executed in-line is the outer function and its return value (the
constructor reference) is assigned to the variable MyObject.

> Argh, I know it must be like dancing with an elephant to help
>me here, so I'll definitely understand if you just tell me to go
>read a book ;)

If I knew a book that would help I might [1] but this dance is more fun
than the "will you pleeeeeeeeease show us the ****** script" dance that
half the other posters insist on starting with.

Richard.

[1] If you feel like reading a book anyway, have your read "Godel,
Echer, Bach: an Eternal Golden Braid" by Douglas R. Hofstadter yet?


Nikos Diamantis

unread,
Jul 2, 2003, 4:45:59 AM7/2/03
to
e?

--
mailto:nd...@cs.ntua.gr
Nikolaos A. Diamantis
/v / /< </ /| <-\ </ > <-\.
<| / <-\ /v| <-\ /v 7 /-/ >

Daniel

unread,
Jul 2, 2003, 6:38:58 AM7/2/03
to
I think I get it now... [This is how I get it:] At the time of declaring
"var MyObject = function(){...", scriptly speaking (hey, nice phrase ;), the
function is just a function like any other function. The fact that it
contains a constructor and that it's gonna "morph" to functionally "become"
this constructor is yet unknown, since at this time all the function does is
occupy memory.

Then, we have the first (and last) execution of *that particular* function
when we (if we read it literally (and I still do that a lot ;)) try to
instantiate it *as if it were* an object constructor. Javascript says, "you
want an instance of that object?" and checks to see what "that object" is,
i.e. the function is evaluated. The function starts its work and ends up
returning its inner constructor function, but not just that, because if it
did, you'd end up using the "new" keyword on an object constructor
*function* object, and not an object *constructor*. No, it uses that one-off
thingie to evaluate the function object to become the object constructor, so
that the assignment argument becomes valid, and the "test" var becomes an
instance of what the MyObject is *now*, which is the object constructor
inside the function is was before. I actually understand it as if the
constructor inside "MyObject" effectively hijacks the variable name and
reference to "MyObject", cutting its connection to the public while
retaining access to its properties and methods for its own members (the
closure).

Now, at every new MyObject instantiation, using "new" on "MyObject" doesn't
execute the orginial function (that reference is lost), but reaches straight
inside it to the object constructor class that provides all its instances
with access to its outer function's resources. (And it can keep track of the
counter since incrementCounter is now an outer function to itself :)

Did I get it? =)

On a side note, since English isn't exactly my mother tongue, and although I
believe I'm better at it than many of my fellow Danes (well, maybe not Lasse
, but others ;), I do have a tendency to mix up words and phrases, and
sometimes simply talk nonsense (also in the text above, I'm sure). Of course
it doesn't help either that I'm learning a programming language through a
foreign language (I mean, phrases like "The primary purpose of the inline


execution of the outer function is to provide a closure to contain private

static (class) members" I have to read a few times before they sink in,
hehe). I apologize for when this results in having to repeat and rephrase
things to me that should be clear the first time, and when it makes me seem
even more daft than I am ;)

That said, I have never understood objects better than I do right now! =)

Thank you, Richard! For your time, your patience, your links, and book tips
=)

Daniel

PS:


> If you feel like reading a book anyway, have your read "Godel,
> Echer, Bach: an Eternal Golden Braid" by Douglas R. Hofstadter yet?

No, I haven't, and I don't even know what it is... I'll check it out on
amazon, see if it looks interesting to me :) Thanks!

Daniel

unread,
Jul 2, 2003, 7:28:31 AM7/2/03
to

"Daniel" <sorry-n...@i-get-virus-and-spam.com> wrote in message
news:3f02b635$0$97201$edfa...@dread12.news.tele.dk...

> > If you feel like reading a book anyway, have your read "Godel,
> > Echer, Bach: an Eternal Golden Braid" by Douglas R. Hofstadter yet?
> No, I haven't, and I don't even know what it is... I'll check it out on
> amazon, see if it looks interesting to me :) Thanks!

Just visited amazon, and it sounds incredibly interesting! I've actually
been missing something like this - last week I saw an animated movie called
"Waking Life" which is very philosophical, and it made me wish for some kind
of philosophical approach to programming, which often seems kind of "dry".
So you can imagine, I can't wait to read this book =)

But since I live in Denmark, the shipping is gonna cost me more than the
actual book, so I thought I might as well order a few books. So if you have
any suggestions to other good books you've read that one "simply must read",
I'd be glad to hear it :)

Thanks,
Daniel


PS: If you haven't seen "Waking Life", I heartily recommend it. It may turn
out to be pop philosophy, though (I don't have enough philosophy experience
to be a credible judge on that ;)

Daniel

unread,
Jul 2, 2003, 10:41:16 AM7/2/03
to

"Richard Cornford" <Ric...@litotes.demon.co.uk> wrote in message
news:bds30l$kqs$1$830f...@news.demon.co.uk...
> function constructor(id){ //class constructor.
> this.id = id;
> var self = this;

Do you really mean this? I mean, "self" is a reference to the current
document...? And if you do mean this, couldn't this cause problems?


Richard Cornford

unread,
Jul 2, 2003, 1:27:22 PM7/2/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> wrote in message
news:3f02ef0f$0$97201$edfa...@dread12.news.tele.dk...

>
>"Richard Cornford" <Ric...@litotes.demon.co.uk> wrote in message
>news:bds30l$kqs$1$830f...@news.demon.co.uk...
>> function constructor(id){ //class constructor.
>> this.id = id;
>> var self = this;
>
>Do you really mean this?

Yes.

>I mean, "self" is a reference to the current document...?

Current window (or global object) not document.

>And if you do mean this, couldn't this cause problems?

Browsers that provide a reference to the global object under the global
property name "self" also provide that reference under the property name
"window", so while the code within this object constructor cannot use
"self" to refer to the global object (because it will resolve as the
local variable "self") the global object has not been rendered
inaccessible to the constructor and the global "self" property is
unaffected by the existence of a locally scoped variable with the same
name.

"self" might not be the best identifier to use because of the possible
confusion with "self" as a property of the global object that refers
back to that object. Lasse, for example, used - var myself = this; -
earlier in this thread. Douglas Crockford uses - var self = this; - as I
do.

The "self" or "myself" variables are named for the concept that they
represent. They hold a reference to the object instance so that inner
functions of the constructor can refer to their own object instance
(itself) when they are being executed in the global context. English
speaking programmers are burdened by the fact that the DOM properties
have been named with words relating to concepts in English. Danish
probably offers you a substitute variable name that would represent the
same concept but not risk causing any confusion with the DOM properties.
Along those lines you may have seen Douglas Crockford using "uber" in
his inheritance code because the English word "super" is a JavaScript
reserved word and cannot be used as an identifier.

I have been tending to deal with possible confusion from the other end
and creating my own reference to the global object with the identifier
"global" and using that instead of either "window" or "self" (though I
usually don’t use it in code that I post because that really would be
confusing).

Richard.


Richard Cornford

unread,
Jul 2, 2003, 9:31:11 PM7/2/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> wrote in message
news:3f02b635$0$97201$edfa...@dread12.news.tele.dk...

>I think I get it now... [This is how I get it:] At the time
>of declaring "var MyObject = function(){...", scriptly speaking
>(hey, nice phrase ;), the function is just a function like any
>other function. The fact that it contains a constructor and that
>it's gonna "morph" to functionally "become" this constructor is
>yet unknown, since at this time all the function does is occupy
>memory.

It is getting there but you seem to be seeing a bit too much 'magic'.
"morph" and "become" imply some sort of transformation of the various
objects involved in this process. In practice none of the objects
involved ever change.

I will start by trying to clarify the role of the on-off function call.
Consider:-

function exampleFunction(){
return new Array();
}

var anObject = exampleFunction();

- In this case a function is defined separately and then called, its
return value (a new Array) assigned to the global variable - anObject -.
The assignment of a value to the - anObject - variable is the very last
operation in the process and - anObject - does not know anything abut
what is happening on the right hand side of the assignment operator (-
= -). Now consider:-

var anObject = funciton(){
return new Array();
}();
^- It is the pair of brackets after the function expression that
execute it (in-line and once only).

- The function has changed from a function definition and is now a
function expression but the only consequence of that is that the
resulting function object is now anonymous (as it now has no identifier
by which it can be referenced) and the function object itself is not
created prior to the execution of this line of code. Apart from that
nothing has changed. From the left hand side of the assignment
operator - anObject - sees no difference at all, it ends up holding a
reference to an Array. On the right hand side of the assignment the
process has not changed; a function is being executed and the value that
it returns (the reference to a new Array object) is the result of the
operation and is assigned to the left hand side of the - = -. The
difference is that the code that defines the function is now in-line but
the nature of the objects involved is identical.

The one-off function in my example class script is just a normal
function object, it is executed and it returns a value. That value just
happens to be a reference to a function object.

Function objects do not recognise a distinction between constructor
functions and non-constructors. That distinction is only in the mind of
the code's author, which will influence how they use the function. If
the - new - keyword is used when a function is invoked the interpreter
will internally create an Object and make a reference to that object be
the - this - value during the subsequent execution of the function, and
then, in the absence of any other - return - statements, it will return
that object. If the function is invoked without the - new - keyword
the - this - reference will be determined by the context in which the
function is called and the return value is undefined if no explicit -
return - statement is provided.

function exampleFunction2(){
var a = 'anyThing';
//but no explicit return value.
}

alert( typeof exampleFunction2 ); //not executed and alerts 'function'

alert( typeof exampleFunction2() ); //executed but alerts 'undefined'

alert( typeof new exampleFunction2() ); //called as a constructor and
// alerts 'object'

Obviously invoking a function that has a - return - value with the -
new - keyword is pointless as the Object that is internally constructed
and used as the - this - value is just wasted and gets thrown away at
the end of the function invocation.

function exampleFunction3(){
var a = 'anyThing';
return a;
}

alert( typeof exampleFunction3() ); //executed and alerts 'string'

alert( typeof new exampleFunction3() ); //called as a constructor but
// alerts 'string'
//The internally created object is thrown away.

So a constructor is just a normal function object, it is the use of
the - new - keyword that constructs a new Object and the way that the
function body is written that makes it suitable to be a constructor.

>Then, we have the first (and last) execution of *that particular*
>function when we (if we read it literally (and I still do that a
>lot ;)) try to instantiate it *as if it were* an object constructor.
>Javascript says, "you want an instance of that object?" and checks
>to see what "that object" is, i.e. the function is evaluated.

The one-off execution of the outer function does not involve the use of
the - new - keyword so no attempt is made to create an instance of any
object at this point. Just the execution of a function that has a return
value, that happens to be a reference to a function object.

>The function starts its work and ends up returning its
>inner constructor function, but not just that, because if it
>did, you'd end up using the "new" keyword on an object constructor
>*function* object, and not an object *constructor*.

JavaScript only has one type of function object, it is the code within
the returned inner function body that makes it appropriate to use it as
a constructor.

>No, it uses that one-off thingie to evaluate the function
>object to become the object constructor, so that the
>assignment argument becomes valid,

The one-off thingie returns a reference to a function object. Nothing
"becomes", the function object referred to is, was and always will be a
function object. It is just a function object that was written to be a
constructor (it contains appropriate code).

>and the "test" var becomes an instance of what the MyObject is
>*now*, which is the object constructor inside the function is
>was before.

There is no "before" for the MyObject variable. The entire right hand
side of the assignment expression has finished prior to MyObject being
assigned the result (the reference to the inner function that can be
used as an object constructor).

>I actually understand it as if the constructor inside "MyObject"
>effectively hijacks the variable name and reference to "MyObject",
>cutting its connection to the public while retaining access to its
>properties and methods for its own members (the closure).

There is no "hijacking" of MyObject as it has never been aware of the
execution of the one-off function on the right hand side of the
assignment. It only ever holds a reference to one object, the function
object returned by the one-off function call.

>Now, at every new MyObject instantiation, using "new" on "MyObject"
>doesn't execute the orginial function (that reference is lost), but
>reaches straight inside it to the object constructor class that
>provides all its instances with access to its outer function's
>resources. (And it can keep track of the counter since
>incrementCounter is now an outer function to itself :)

I would not have put the word "class" at the end of "the object
constructor class" as it seems to confuse the relationship between
classes and their instances. The constructor, when invoked with the -
new -keyword, returns an instance of a Class. So, every new MyObject
instantiation, using "new" on "MyObject" reaches straight inside the
closure formed when the one-off function was executed to the Class
constructor and thus provides all its instances with access to the other
inner functions and variables of the outer function.

> Did I get it? =)

You are getting closer and are not that far off now.

<snip>
> ..., since English isn't exactly my mother tongue, ...
<snip>

You should not worry about that. To date you have managed to communicate
in English better than many native English speakers that I have known,
and having to read a sentence about the details of a programming
language more than a couple of times before grasping it is something
that I have plenty of experience of.

It also won't take you a fraction of a second to guess how good my
Danish is (hint: zero).

Richard.


Daniel

unread,
Jul 3, 2003, 3:31:58 AM7/3/03
to

"Richard Cornford" <Ric...@litotes.demon.co.uk> wrote in message
news:bdv4lr$3s4$1$8300...@news.demon.co.uk...

> Current window (or global object) not document.

This is my Javascript Bible shining through, I guess, as it puts window
synonymous with document in most cases, since only one document can exist in
a given window, and a given window cannot be referenced within itself
without a document. I get it mixed up sometimes because of that =)

> Browsers that provide a reference to the global object under the global
> property name "self" also provide that reference under the property name
> "window", so while the code within this object constructor cannot use

Are there any browsers that don't? Should I use window instead?

> English
> speaking programmers are burdened by the fact that the DOM properties
> have been named with words relating to concepts in English. Danish
> probably offers you a substitute variable name that would represent the
> same concept but not risk causing any confusion with the DOM properties.

Yes, and a lot of people do use Danish phrases. I don't use Danish words
myself though, as I find the text more confusing (and less pretty) to read
with all the switching between languages. Besides, it would often require me
to substitute our special characters, æ, ø, and å, with their a-z
equivalents, ae, oe, and aa, which I definitely don't like ;) Besides, you
never know when a foreigner is hired to revise your code, in which case it
would be courteous to help out a little by making it universally
understandable.

> I have been tending to deal with possible confusion from the other end
> and creating my own reference to the global object with the identifier
> "global" and using that instead of either "window" or "self" (though I
> usually don't use it in code that I post because that really would be
> confusing).

That's a good idea, one I think I'll adopt. =)

Thanks,

Daniel

unread,
Jul 3, 2003, 11:31:05 AM7/3/03
to

"Richard Cornford" <Ric...@litotes.demon.co.uk> wrote in message
news:be0119$ln8$1$8302...@news.demon.co.uk...

> It is getting there but you seem to be seeing a bit too much 'magic'.
> "morph" and "become" imply some sort of transformation of the various
> objects involved in this process. In practice none of the objects
> involved ever change.

Man, I wish I had you here so I could scoop that brain of yours ;) I've been
banging my head all day... First, let me say that my use of words like
"morph" and "become" shouldn't be taken too literally, at least not in the
programmatical context; the context should be my way of putting my
understanding into human, easily digestible, words.

That said, I did mean that the object was changed somehow, but I see your
point that everything stays the same (except from variable values,
ofcourse).

But still, I don't see the anonymity of the "original" MyObject function
being the result of function expression, since it isn't anonymous before
after it's been called. Up until that point it does exist as MyObject, as a
definition yes, but it still has a reference... To me, a truly anonymous
function expression would be something like

myArray.sort(function(a,b){ return subCmp(a[label],b[label]); });

...And then you write this:

> var anObject = funciton(){
> return new Array();
> }();
> ^- It is the pair of brackets after the function expression that
> execute it (in-line and once only).

But how can that be true? As I see it, the (); calls whatever's returned by
the "anObject" function, which makes perfect sense when you try to execute
this code, and Javascript errors out with either "object doesn't support
this action", or "function expected" if I remove the new keyword - the only
object that can be suffixed by (); is a function, right? So the only place
Javascript could be expecting a function would be before the (); which is
the "anObject" function, which then *must* return a function, or Javascript
would error out like it does with this code. And, if I write

var oneOff = function() {
document.write("1");
constructor = function() {
document.write(" 2");
}
return constructor
}();

var test = new oneOff();

- I get "1 2", which means oneOff is parsed before the inner function, yes?
So, as I see it, if,

var oneOff = function(){ /*code*/ }();

then,

var varName = new oneOff();

can be read

<varname> is assigned <anonymous function expression returning an
object>

- but the fact that the function expression is anononymous isn't known until
it's called (at least not to the parser, because it has a reference,
"oneOff", so how could it be anonymous?), which is why we're able to call it
at all, via the reference "oneOff". But, after it's called, "oneOff" is no
longer a reference to "oneOff", but to "constructor". This is where my image
of "reference hijacking" came from :P - before the first instantiation,
"oneOff" was a reference to a one-off function, but now it's a reference to
an object returned by the one-off function. I can see that the "hijacking"
term is bad because it indicates that it's the same reference that's been
"unplugged" from "oneOff" and "plugged into" the "constructor" function,
which probably isn't the case. But "oneOff" used to hold a reference to a
function definition, and now, after evaluating that definition, it holds a
reference to something else... Hm...

Also, realizing that I didn't properly understand the "one-off" term caused
me more and more grief, while I wasn't able to find any info on it in my
Bible or on Google. Before I finally looked it up in the dictionary
(should've done that first thing), I understood it as "more than one
statement/function executed in one go", but seeing it described as
"something done once only" cleared that up :) Except that it just added fuel
to my apparently false mind image of the reference being "hijacked", since
if it weren't, then the next time you'd use "new oneOff" you'd be calling
the same code again, and that would conflict with the term itself. I'm
confused :(

> - The function has changed from a function definition and is now a
> function expression but the only consequence of that is that the
> resulting function object is now anonymous (as it now has no identifier
> by which it can be referenced) and the function object itself is not

Doesn't this in a way confirm my image of the reference to the "original"
(as I like to call it) "myObject" being "hijacked" (I know ;) by
"constructor"? I mean, it did have a reference when we called it the first
time (just before it changes to a function expression)? And after this, the
referenced element is the product of the expression, i.e. the constructor?

> >Then, we have the first (and last) execution of *that particular*
> >function when we (if we read it literally (and I still do that a
> >lot ;)) try to instantiate it *as if it were* an object constructor.
> >Javascript says, "you want an instance of that object?" and checks
> >to see what "that object" is, i.e. the function is evaluated.
>
> The one-off execution of the outer function does not involve the use of
> the - new - keyword so no attempt is made to create an instance of any
> object at this point. Just the execution of a function that has a return
> value, that happens to be a reference to a function object.

But "this point" *is* the moment of assigning an instance of an object to a
variable. I know it's not because of the "new" keyword that the one-off
thingamajig works, and that the process would happen regardless of how the
function was called, that it's just the process of evaluating it that makes
things happen. But isn't this the way the parser (perhaps I mean compiler?)
works? I.e. it starts reading, and says

1) var : "Aha, you want a variable, what should we call it?"
2) objectInstance : "Great name!"
3) = : "Okay, sure, let's assign it a value right away"
4) new : "Oh, so you want an instance of an object, do you? Let's see
what that object could be."
5) MyObject(); : "Well, I'll just evaluate that and get back to you"
[evaluating, finding the one-off function, evaluating it, doing parser
stuff, returning the constructor](*) "Okay, I have the guidelines now, let's
make that instance" [making an instance of the constructor, then assigning
it to "objectInstance"]

(*) And this is when all the magic ;) happens?

Am I really that far off or is it just my handicapped Javascript/English
vocabulary and my tendency to use (bad) metaphors damaging my ability to
write concisely? (Oh, thanks for picking me up about my English ;)

> >The function starts its work and ends up returning its
> >inner constructor function, but not just that, because if it
> >did, you'd end up using the "new" keyword on an object constructor
> >*function* object, and not an object *constructor*.
>
> JavaScript only has one type of function object, it is the code within
> the returned inner function body that makes it appropriate to use it as
> a constructor.

What I meant by "object constructor *function* object" and "object
*constructor*" was this:

var blahblah = function() {
constructor = function() {
};
return constructor;
}

var myconstructor = blahblah();
^ That would become my "object constructor *function* object"

var myinstance = new myconstructor();
^ And that would become my "object *constructor*"

I know that was terribly phrased, but my understanding here was that with
Mr. One-Off, I'd have just one call creating "myinstance" because One-Off
incorporates the "myconstructor" step in "blahblah" (I know that's not
exactly it or all of it, but that was the particular effect I was talking
about there)

> I would not have put the word "class" at the end of "the object
> constructor class" as it seems to confuse the relationship between
> classes and their instances. The constructor, when invoked with the -

I confused myself there, actually =) I'm not used to classes, since in
Actionscript everything is essentially an object (or a prototype). I just
saw it in your code, and thought, well... Don't know what I thought, really
:P

Man, I really want the next words you say to be, "Actually I think you *do*
get it, Daniel, but for God's sake, man, work on your ability to precisely
explain what you mean!"

If nothing else, I truly understand why

alert(function(){ return function() { return true; }}()());

Gives me an alert box with "true" written in it.

Argh! :) It's tough work getting smarter. But FUN!!!

Daniel

PS: Richard, thank you for all this, it's really great to have my mind
challenged - it's been a while ;)!

Lasse Reichstein Nielsen

unread,
Jul 3, 2003, 12:14:26 PM7/3/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> writes:

> First, let me say that my use of words like "morph" and "become"
> shouldn't be taken too literally, at least not in the programmatical
> context; the context should be my way of putting my understanding
> into human, easily digestible, words.

That is a step on the way to understanding, making the concepts fit
inside ones head. However, words that make sense in your mind, often
ends up making little or no sense when taken out of that context. :)

Or, as somebody once said: You haven't really understood something
before you can explain it clearly. (He was right!)

> But still, I don't see the anonymity of the "original" MyObject function
> being the result of function expression, since it isn't anonymous before
> after it's been called. Up until that point it does exist as MyObject, as a
> definition yes, but it still has a reference...

I think you are putting the parentheses in the wrong places. The code was

var anObject = function(){...} ();

I think you are reading it as

(var anObject = function(){...}) ();

i.e., assign the function value to the anObject variable first, then
call it. This is syntacitcally illegal, since the "var" keyword makes
it a declaration, and declarations have no value. The correct way of
reading it, however, is

var anObject = (function(){...} ());

i.e., create anonymous function, call it, and assign the return value to
the anObject variable.

I had to read it twice too, to be sure what happened. I would have put
the parentheses there to disambiguate.

> To me, a truly anonymous function expression would be something like
>
> myArray.sort(function(a,b){ return subCmp(a[label],b[label]); });
>
> ...And then you write this:

Indeed.



> > var anObject = funciton(){
> > return new Array();
> > }();
> > ^- It is the pair of brackets after the function expression that
> > execute it (in-line and once only).
>
> But how can that be true? As I see it, the (); calls whatever's returned by
> the "anObject" function,

There is no "anObject" function. If you bound the function first, say using
(anObject = function(){...}) ();
(without the "var" so it is legal), then anObject would be a function, but
the "()" would call that function, not the value returned by it. The returned
value is actually lost.

> And, if I write
>
> var oneOff = function() {
> document.write("1");
> constructor = function() {
> document.write(" 2");
> }
> return constructor
> }();
>
> var test = new oneOff();
>
> - I get "1 2", which means oneOff is parsed before the inner function, yes?

The execution goes like this:

1 : create anonymous function (a "function expression"):
function() { document.write ... return constructor}
2 : call the function from 1
2.1 : execute document.write("1")
2.2 : create an anonymous function (a "function expression"):
function() {document.write(" 2");}
2.3 : assign the result of 2.2 to the new global variable "constructor".
2.4 : return the value of the global variable "constructor". This is the
result of 2.
3 : assign the result of 2 to the local variable "oneOff".
4 : use the value of the variable "oneOff" as a constructor with
no arguments (new ...()). That is, create a new object and
call the function with "this" pointing to the new object.
4.1 : execute document.write(" 2")
4.2 : since nothing is returned, the result of the "new"-expression (and
the result of 4) is the new object.
5 : assign the result of 4 to the variable "test".

> So, as I see it, if,
>
> var oneOff = function(){ /*code*/ }();

this is somehow similar to the pseudo-code:
var oneOff = /* code */ ;
except that code need not be an expression. It can contain statements and
local variable declarations. Writing
function () { ... }()
merely creates a local block and a scope.

...


> What I meant by "object constructor *function* object" and "object
> *constructor*" was this:
>
> var blahblah = function() {
> constructor = function() {
> };
> return constructor;
> }

> var myconstructor = blahblah();
> ^ That would become my "object constructor *function* object"

I would just call it "constructor function"



> var myinstance = new myconstructor();
> ^ And that would become my "object *constructor*"

I would just called it "object", "instance of myconstructor" or
"constructed object". Shorter is (sometimes) better :)

> I confused myself there, actually =) I'm not used to classes, since in
> Actionscript everything is essentially an object (or a prototype). I just
> saw it in your code, and thought, well... Don't know what I thought, really
> :P

That is much closer to Javascript than most languages then. Javascript
is a prototype based (as oppesed to class based) object oriented language.

I sometimes wish there was a clone method on all objects, but one can
make it oneself:

Object.prototype.clone = function () {
function myConstructor = function(){};
myConstructor.prototype = this;
return new myConstructor();
}


> Man, I really want the next words you say to be, "Actually I think you *do*
> get it, Daniel, but for God's sake, man, work on your ability to precisely
> explain what you mean!"

> If nothing else, I truly understand why
>
> alert(function(){ return function() { return true; }}()());
>
> Gives me an alert box with "true" written in it.

In that case, I actually think you *do* get it (apart from a minor
detail about how function application and assignment associates),
Daniel, but for your own sake, work on your ability to precisely
explain what you mean!


> Argh! :) It's tough work getting smarter. But FUN!!!

> PS: Richard, thank you for all this, it's really great to have my mind


> challenged - it's been a while ;)!

You'll go far with that attitude :)

Daniel

unread,
Jul 3, 2003, 1:55:45 PM7/3/03
to

"Lasse Reichstein Nielsen" <l...@hotpop.com> wrote in message
news:el17io...@hotpop.com...

> That is a step on the way to understanding, making the concepts fit
> inside ones head. However, words that make sense in your mind, often
> ends up making little or no sense when taken out of that context. :)

Tell me about it! Hehe =)

> Or, as somebody once said: You haven't really understood something
> before you can explain it clearly. (He was right!)

Come to think of it, that's pretty much how I know I've really understood
something, which is probably why I keep babbling and babbling on about this,
because I can't say that I'd be able to teach someone else this and know I
was telling the truth :) Also, I'm pretty sure I could use these skills now
without causing errors, but I guess the quest right now really is that I
want to be able to explain it clearly. So right on!

> I think you are putting the parentheses in the wrong places. The code was
>
> var anObject = function(){...} ();
>
> I think you are reading it as
>
> (var anObject = function(){...}) ();
>
> i.e., assign the function value to the anObject variable first, then
> call it. This is syntacitcally illegal, since the "var" keyword makes
> it a declaration, and declarations have no value. The correct way of
> reading it, however, is
>
> var anObject = (function(){...} ());

GREAT way to put it! Actually, I think of the parentheses like this:

var anObject = (function(){...})();

with (function(){...}) being evaluated first, then the return value of that
being evaluated by (); then the return value of that being assigned to
anObject.

But that's not entirely true, because at the point of assigning anObject a
value, which, as I understand, is what is happening here, I don't see any
evaluation being made just yet, at that point I see it as you put it, that
is:

var anObject = (function(){...}();)

in the sense that at this particular instant in time, anObject holds a
reference to all definitions inside these parentheses, and these definitions
will stay "untouched" or "unexecuted" or "unevaluated" or "unprocessed" ;)
until anObject is called in another context. So when I say above that,
"...the return value of that being assigned to anObject", that would require
its invocation context to be simply:

anObject();

However, the way we use it, as an object construct -

var myInstance = new anObject();

- I see "...the return value of that being assigned to anObject", but
"anObject" in this context being nothing more than the courier of the
reference it holds inside, i.e. returns to an expression, i.e. assigns to
the given variable. In this context, to properly explain this with
parenthesis, I'd probably write a combination of the former two:

((function(){...})();)

- and lose the "var anObject" assignment part because that would be implied,
not as a variable holding the evaluated contents of the parentheses above,
but the yet unevaluated definition contents - the actual evaluation and
solution of the parentheses take place at that particular time and not
before.

That's pretty much how I understand that.

> > > var anObject = funciton(){
> > > return new Array();
> > > }();
> > > ^- It is the pair of brackets after the function expression that
> > > execute it (in-line and once only).
> >
> > But how can that be true? As I see it, the (); calls whatever's returned
by
> > the "anObject" function,
>
> There is no "anObject" function. If you bound the function first, say
using
> (anObject = function(){...}) ();
> (without the "var" so it is legal), then anObject would be a function, but
> the "()" would call that function, not the value returned by it. The
returned
> value is actually lost.

I'm glad you write this, because that's actually exactly what I mean =) (See
why I say you're better at English than I am? ;)

> > And, if I write
> >
> > var oneOff = function() {
> > document.write("1");
> > constructor = function() {
> > document.write(" 2");
> > }
> > return constructor
> > }();
> >
> > var test = new oneOff();
> >
> > - I get "1 2", which means oneOff is parsed before the inner function,
yes?
>
> The execution goes like this:
>
> 1 : create anonymous function (a "function expression"):
> function() { document.write ... return constructor}
> 2 : call the function from 1
> 2.1 : execute document.write("1")
> 2.2 : create an anonymous function (a "function expression"):
> function() {document.write(" 2");}

With you so far.

> 2.3 : assign the result of 2.2 to the new global variable "constructor".

Global? I thought it'd be a private member of oneOff?

> 2.4 : return the value of the global variable "constructor". This is the
> result of 2.
> 3 : assign the result of 2 to the local variable "oneOff".
> 4 : use the value of the variable "oneOff" as a constructor with
> no arguments (new ...()). That is, create a new object and
> call the function with "this" pointing to the new object.
> 4.1 : execute document.write(" 2")

This is executed as a result of the instantiation of the constructor object,
right? Not Mr. One-Off?

> 4.2 : since nothing is returned, the result of the "new"-expression (and
> the result of 4) is the new object.
> 5 : assign the result of 4 to the variable "test".

I'm with you all the way (except for the global constructor variable), and
thank you for putting it like this, because the sequence was a bit messy in
my head, seeing it like this makes it perfectly clear :)

<snip>


> I would just call it "constructor function"

<snip>


> I would just called it "object", "instance of myconstructor" or
> "constructed object". Shorter is (sometimes) better :)

<snip>

Oh yes =)

> That is much closer to Javascript than most languages then. Javascript
> is a prototype based (as oppesed to class based) object oriented language.

That's what I thought, since they're both ECMA-based, but when I see "class"
being used, I suddenly start wondering... I do that a lot...

> > If nothing else, I truly understand why
> >
> > alert(function(){ return function() { return true; }}()());
> >
> > Gives me an alert box with "true" written in it.
>
> In that case, I actually think you *do* get it (apart from a minor
> detail about how function application and assignment associates),
> Daniel, but for your own sake, work on your ability to precisely
> explain what you mean!

Woohoooo!!! =)

> > Argh! :) It's tough work getting smarter. But FUN!!!
>
> > PS: Richard, thank you for all this, it's really great to have my mind
> > challenged - it's been a while ;)!
>
> You'll go far with that attitude :)

You just wait and see, one day you guys will be asking ME for help! *L* ;)

Thanks mate!

Daniel


PS: I think this thread is getting really good reading for newbies trying to
understand stuff like this, don't you guys? Your expertise and my daftness
is a winning cocktail! We oughta write some books! ;)

Lasse Reichstein Nielsen

unread,
Jul 3, 2003, 5:55:28 PM7/3/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> writes:

> GREAT way to put it! Actually, I think of the parentheses like this:
>
> var anObject = (function(){...})();
>
> with (function(){...}) being evaluated first, then the return value of that
> being evaluated by (); then the return value of that being assigned to
> anObject.

Here you are using confuzing terminology (saying "return value" twice
even though there is only one function call). I'll try to be very
precise:

"function (){...}" is a function *expression* (a sequence of
characters that match a production of the grammar called "function
expression"). It is an expression (rather than, e.g., a statement), so
it can be evaluated to a value.

That value is a function *value* (you say "return value", but there is
nothing being returned yet, the body of the function is not evaluated
at this point). Functions in Javascript are objects which have an
internal method called "[[Call]]".

"(function(){...})()" is again an expression, in this case a function
application. It consists of two parts, the *expression* before the
parentheses, which should (if the program is correct) evaluate to a
function *value*, and the argument expressions og which there are zero
in this case.

To evaluate a function application, first evaluate the expression in
the function-position. In this case it is a function expression, so
it directly evaluates to an (anonymous) function value. Then evaluate
the arguments, in this case it is trivial. Finally, call the function with
the arguments. At this point, the body of the function is evaluated.
The reteurn value of *that* is the value of the application expression.

"var anObject = function(){...}();" is not an expression, it is a statement.
More precisely, it is a "variable declaration and initalization" statement.
The Javascript interpreter already noticed that "anObject" was declared
as a local variable, it checks that before executing anything, so the scope
of the variable can precede its declaration.

To find the effect of a statement, it is executed (not evaluated, as
it doesn't have to have a value). To execute an assignment (what an
initialization statement really is), you first evaluate the right-hand
side expression. In this case, it is the return value of calling the
anonymous function. Then, and only then, is the "anObject" variable
bound to that value. Until this, it has been undefined.

That value, the return value of the call to the anonymous function
(which we have no reference to otherwise[1], so it will never be
called again) just happens to be a function itself, a completely
different function.

> But that's not entirely true, because at the point of assigning anObject a
> value, which, as I understand, is what is happening here, I don't see any
> evaluation being made just yet, at that point I see it as you put it, that
> is:
>
> var anObject = (function(){...}();)
>
> in the sense that at this particular instant in time, anObject holds a
> reference to all definitions inside these parentheses, and these definitions
> will stay "untouched" or "unexecuted" or "unevaluated" or "unprocessed" ;)
> until anObject is called in another context.

Not so. The parentheses (they are curved, not squiggly) are only grouping.
They don't delay the execution. Javascript is a strict language, so you don't
pass around unevaluated code just like that.

> I'm glad you write this, because that's actually exactly what I mean =) (See
> why I say you're better at English than I am? ;)

Years of practice writing academic English will do that to you. I can
talk for hours about closures, but I have little to no knowledge of
the names of kitchen utensils :)



> > 2.3 : assign the result of 2.2 to the new global variable "constructor".
>
> Global? I thought it'd be a private member of oneOff?

The constructor variable has not been declared local by a "var
constructor" declaration. Therefore it defaults to being global.

> > 2.4 : return the value of the global variable "constructor". This is the
> > result of 2.
> > 3 : assign the result of 2 to the local variable "oneOff".
> > 4 : use the value of the variable "oneOff" as a constructor with
> > no arguments (new ...()). That is, create a new object and
> > call the function with "this" pointing to the new object.
> > 4.1 : execute document.write(" 2")
>
> This is executed as a result of the instantiation of the constructor object,
> right? Not Mr. One-Off?

The value of the variable "oneOff" is a function. That function's body
contains 'document.write(" 2")'. When writing "new oneOff()" you use
that function as a constructor, but that includes calling it as a function.
The "document.write" is executed as part of the expression "new oneOff()".

> > That is much closer to Javascript than most languages then. Javascript
> > is a prototype based (as oppesed to class based) object oriented language.
>
> That's what I thought, since they're both ECMA-based, but when I see "class"
> being used, I suddenly start wondering... I do that a lot...

You can emulate classes in Javascript, and people sometimes refer to
elements created using the built in constructors (e.g., Array) as
"instances of the class Array". It is, however, people used to class
based languages that are trying to hammer in a screw.

Needless detail on how objects are created:

Objects are, obviously, an important datatype for Javascript. As I
said earlier, functions are objects with some extra functionality, and
so are Regular Expressions and a lot of other utility objects.

All objects have a property called "constructor". It refers to the
function that was (or could have been) used as a constructor to create
the object. If you write "var x={};" then "x" refers to a new,
(almost) empty object. The constructor for it is the one called
"Object". The constructor of an array is "Array", and so on.

Each function can be used as a constructor and therefore has a
property (remember, they are objects too) called "prototype". When you
look for a property of an object, it first checks if the object has
had that property assigned to it. If not, it checks if it is a
property of its prototype, and if not, it continues down the prototype
chain (I haven't checked where it ends, but probably at Object.prototype).

Quiz: What does the following do?
---
var x = new Object();
Object.prototype.foo = 42;
alert(x.foo);
---

When you call a function as a method of an object, the "this" keyword
will refer to that object. That is:
---
var x = new Object();
x.foo = function () {return this;};
alert(x == x.foo());
---
will alert "true".
It is the "." notation (or the equivalent []-notation) that marks a
function call as a method invocation. If you changed the above to:
---
var x = new Object();
x.foo = function () {return this;};
var bar = x.foo;
alert(x == bar());
---
it alerts "false", even though "x.foo" and "bar" both refer to the
exact same function object. It is the way the function is called that
sets the "this" keyword's value. When you call a function directly,
and not as part of an object, then the "this" keyword refers to the
global object, where the global variables live.


Since there are no classes in Javascript, the term "constructor" might
also be a little misleading. As I said, any function can be used as a
constructor. What happens when you write
new foo(42);
is that you call the function "foo" with the argument "42". However,
where a normal function call of that kind would have set the "this"
reference to the global object, and a method invocation would set
"this" to the object of the method, the "new" makes sure that the
"this" keyword refers to an entirely new object. If the foo function
doesn't return something (or if it returns something that is not an
object), that new object is the value of the entire expression. If
it returns another object, they object will be the value of the "new"
expression.

---
function foo(x) {
this.n=x;
}

foo(37); /* sets this.n = 37 with this == global object */

var o1 = new Object();
o1.bar = foo;
o1.bar(42); /* sets this.n = 42 with this == o1 */

var o2 = new foo(87); /* sets this.n = 87 with this == new object == o2 */

alert(n +","+ o1.n +","+ o2.n); /* alerts "37,42,87" */
---

Richard Cornford

unread,
Jul 3, 2003, 10:05:40 PM7/3/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> wrote in message
news:3f044c3c$0$97223$edfa...@dread12.news.tele.dk...
<snip>

> That said, I did mean that the object was changed somehow,
>but I see your point that everything stays the same (except
>from variable values, ofcourse).
>
>But still, I don't see the anonymity of the "original" MyObject
function
>being the result of function expression, since it isn't anonymous
before
>after it's been called. Up until that point it does exist as MyObject,
as a
>definition yes, but it still has a reference... To me, a truly
anonymous
>function expression would be something like
>
> myArray.sort(function(a,b){ return subCmp(a[label],b[label]); });
>
> ...And then you write this:
>
>> var anObject = funciton(){
>> return new Array();
>> }();
>> ^- It is the pair of brackets after the function
>>expression that execute it (in-line and once only).
<snip>
>... "object doesn't support this action", ...
<snip>

Ops, that's my fault. If you look closely at the way I have spelled
function you will notice that the t and the i have been transposed. One
of the hazards of touch typing into a word processor instead of a
syntax-highlighting text editor. Though I am surprised that I did not
notice Word complaining about the spelling, but there is a tendency to
ignore highlighted spelling mistakes when entering code in Word. Sorry
if that was confusion, correct the spelling an it will work as
advertised.

<snip>

>... . I can see that the "hijacking" term is bad because it indicates


>that it's the same reference that's been "unplugged" from "oneOff"
>and "plugged into" the "constructor" function, which probably isn't
>the case. But "oneOff" used to hold a reference to a function
definition,
>and now, after evaluating that definition, it holds a reference to
>something else... Hm...

<snip>

My reason for stressing that the assignment operation had a left hand
side (var MyObject) and a right hand side (all the rest of the
statement) was to try and explain how MyObject was only ever assigned
the end result of the right hand side. There is not "hijacking" because
the only value that is ever associated with the MyObject variable is a
reference to a function object that was originally created as the inner
function "constructor" within the execution context of the one-off
function execution.

You seem to be seeing too much happening at once and Lasse is right,
parenthesising the original statement should make the real sequence of
events clearer.

ECMA script assigns precedence to various operations, so while:-

alert( 1 + 2 * 4 );

- could alert 12 or 9 in practice it always alerts 9 because the - * -
operator has higher precedence than the - + - operator. The order of
evaluation of an expression can be altered by using parentheses to
bracket the addition operation - alert( (1 + 2) * 4 ); - which alerts 12
because the addition Is forced to happen before the multiplication
instead of after. Because ECMA Script defines precedence for operations
the original alert statement can be bracketed as - alert( 1 + (2 *
4) ); - and still produce the original result 9. That arrangement of
brackets can be considered the "natural" parenthesising of the
expression. So:-

var MyObject = function(){ . . . }();

- (as a shorthand form of the original example) can "naturally" be
parenthesised as:-

var MyObject = ( ( function(){ . . . } )() );
^- notice that the
statement terminating semicolon must be
outside of the parentheses for this to
remain legal JavaScript syntax. In the
same way as the - var - cannot be placed
within parentheses.

For the interpreter to discover what value to assign to the MyObject
variable it must evaluate the whole of the expression on the right hand
side of the - = -, the contents of the outer set of brackets. The
evaluation of the contents of the outer set of brackets must start with
the contents of the innermost brackets, which contain - function(){ . .
. } -, a truly anonymous function expression. Anonymous because once the
function object has been created the _only_ reference to it is the
result of the evaluation of the innermost bracketed expression. If we
refer to the result of the evaluation of the innermost set of brackets
as - temporaryInternalFunctionReference - and replace those brackets
with that we get:-

var MyObject = ( temporaryInternalFunctionReference() );

The next stage in the process is the evaluation of the contents of the
remaining set of brackets. That step is the execution of the function
object referred to by the result of the evaluation of the contents of
the inner set of brackets. That function is the outer function so the
result of executing it is its return value, the inner function
"constructor" that may later be used as an object constructor.

Having fully resolved the right hand side of the assignment operator,
and acquired the reference to the inner "constructor" function as the
result, The last part of the process is to assign that value to the
MyObject variable.

Up until that final assignment of the reference to the inner
"constructor" function object MyObject has not referred to anything. It
has also never known anything about what is going on to the right of
the - = - operator.
From that point on MyObject can be used with the - new - keyword to
construct objects because it refers to a function object, and because
that function object has been created with code that is appropriate to
an object constructor (and has had additional methods assigned to its
prototype) using - new MyObject("anyString"); - is a reasonable thing to
do and will create a usable object.

<snip>
> ... I.e. it starts reading, and says


>
> 1) var : "Aha, you want a variable, what should we call it?"
> 2) objectInstance : "Great name!"
> 3) = : "Okay, sure, let's assign it a value right away"
> 4) new : "Oh, so you want an instance of an object, do you? Let's
>see what that object could be."
> 5) MyObject(); : "Well, I'll just evaluate that and get back to
>you" [evaluating, finding the one-off function, evaluating it, doing
>parser stuff, returning the constructor](*) "Okay, I have the
guidelines
>now, let's make that instance" [making an instance of the constructor,
>then assigning it to "objectInstance"]

At the point of executing:-

var objectInstance = MyObject();

- the MyObject variable already contains a reference to the inner
function that was defined with the name "constructor". The one-off
function has already been executed and done its work, At this point The
one-off function has no accessible references and will never be executed
again.

<snip>
> ... I'm not used to classes, since in Actionscript everything


>is essentially an object (or a prototype). I just saw it in your
>code, and thought, well... Don't know what I thought, really

As Actionscript is an ECMA implementation everything that we have been
discussing to date will apply equally to Actionscript.

Classes are a concept that is explicit in other object orientated
languages like Java but there is nothing within ECMA Script that
explicitly represents a class.

For comparison, if my original MyObject Class was defined in Java it
would look something like:-

public class MyObject{
private static int counter = 0;
private static void incrementCounter(){
return MyObject.counter++;
}
public String id;
private MyObject self;
private int index;
/* class constructor. */
public MyObject(String id){
this.id = id;
this.self = this; //not needed in Java!
this.index = MyObject.incrementCounter();
};
public int getIndex(){
return this.index;
}
public static int getNoOfInsts(){
return MyObject.counter;
}
public String getId(){
return this.id;
}
}

- As you can see the class is a very concrete structure. It is also a
very final structure, once defined and compiled this class structure
specifies an exact template with which all instances of the Java
MyObject class will be drawn.

The template for an ECMA Script object is much more loosely defined, and
it is also mutable (though you wouldn't often want to do that). If my
original class was defined in the more traditional JavaScript way, as a
separate constructor function and as properties of that function and its
prototype object (the private members must now be public members as
there are no closures to contain them), the results would look like:-

function MyObject(){
this.id = id;
this.self = this; //pointless in an object with no inner functions
this.index = MyObject.incrementCounter();
}
MyObject.prototype.getIndex = function(){
return this.index;
}
MyObject.counter = 0;
MyObject.incrementCounter = function(){
MyObject.counter++;
}
MyObject.getNoOfInsts = function(){
return counter;
}
MyObject.prototype.getId = function(){
return this.id;
}

It is not a single structure but a sequence of statements. Its whole
does still act as a template with which all instances of MyObject are
created. That makes this combined definition of the MyObject
constructor, its properties and the properties of its prototype
analogous to the explicit class definition in Java. However, that
analogy is not explicit in the code, 'Class' is only a convenient
description for all of the interrelated code that is used to specify the
nature of a new object of that 'Class' created with the MyObject
function and the - new - keyword.

It is convenient for programmers who are familiar with object orientated
languages that explicitly define "Class" structures (such as Java) to
apply that term as a label for the totality of JavaScript code that will
be used to create object instances and to extend that label to include
the concept of an object being an instance *of* a particular Class (it
was created with a single set of instance defining code). So "Class" is
also used as a label for the "type" of an object (though JavaScript,
unlike Java, is loosely typed so the "type" that is named by the "Class"
is in the programmers understanding of the code and not a part of the
ECMA Script language, Internally it is just another Object).

>Man, I really want the next words you say to be, "Actually I think
>you *do* get it, Daniel, but for God's sake, man, work on your
>ability to precisely explain what you mean!"

Sorry, I am not going to say that until I can see that you have
understood the behaviour of the in-line one-off function call. You are
getting close and Lasse has posted a very explicit description so I am
confident that you will have it under your belt next time.

As far as precise explanations, that goes both ways. If I was better at
explaining then you might find understanding easier. Seeing where I fail
to get my point across helps me to refine my explanation, which makes
this whole exchange worthwhile in itself. I think that you are doing
your half of the conversation very well. In describing your
understanding at every stage I think that I can see which aspects of the
process I am failing to properly convey.

> If nothing else, I truly understand why
>
> alert(function(){ return function() { return true; }}()());
>
> Gives me an alert box with "true" written in it.

Excellent! One more small step and your there.

Richard.


Daniel

unread,
Jul 4, 2003, 7:29:00 AM7/4/03
to

"Lasse Reichstein Nielsen" <l...@hotpop.com> wrote in message
news:vfujgt...@hotpop.com...

> Years of practice writing academic English will do that to you. I can
> talk for hours about closures, but I have little to no knowledge of

Ah, that explains it then =)

> > Global? I thought it'd be a private member of oneOff?
>
> The constructor variable has not been declared local by a "var
> constructor" declaration. Therefore it defaults to being global.

Ofcourse =)

> > This is executed as a result of the instantiation of the constructor
object,
> > right? Not Mr. One-Off?
>
> The value of the variable "oneOff" is a function. That function's body
> contains 'document.write(" 2")'. When writing "new oneOff()" you use
> that function as a constructor, but that includes calling it as a
function.
> The "document.write" is executed as part of the expression "new oneOff()".

So yes.

> Needless detail on how objects are created:

Never needless =) But most of it wasn't news to me. One thing seems a bit
odd to me, though:

> Since there are no classes in Javascript, the term "constructor" might
> also be a little misleading. As I said, any function can be used as a
> constructor. What happens when you write
> new foo(42);
> is that you call the function "foo" with the argument "42". However,
> where a normal function call of that kind would have set the "this"
> reference to the global object, and a method invocation would set
> "this" to the object of the method, the "new" makes sure that the
> "this" keyword refers to an entirely new object. If the foo function
> doesn't return something (or if it returns something that is not an
> object), that new object is the value of the entire expression. If
> it returns another object, they object will be the value of the "new"
> expression.
>
> ---
> function foo(x) {
> this.n=x;
> }
>
> foo(37); /* sets this.n = 37 with this == global object */

What purpose could this global object serve? And exactly where does it
exist? Since its properties are accessible without a suffix, i.e. global,
It'd be tempting to think of it as a part of the window.document object. Or
are global objects not bound to the window.document object either - are only
objects created with "var blahblah" or "self.blahblah" bound to
window.document? With frames, for example, I can access global variables in
another frame via the document path.

Lasse Reichstein Nielsen

unread,
Jul 4, 2003, 8:39:02 AM7/4/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> writes:

> What purpose could this global object serve?

The global object is the repository of global variables. As such, it is
effectively the top of all scope chains, so it is always in scope. That
is what makes global variables possible at all.

> And exactly where does it exist?

Inside the Javascript interpreter. The existence of the global object
is given by the ECMAscript standard, and all Javascript code is executed
in the context of one global object.

For each function call, the interpreter creates a local scope, the
so-called "variable object", where the parameters and local variables
are properties. These variable objects are not accessible from
javascript, so you cannot use them as objects in your code, they are
merely described as objects in the specification. That allows
implementations to optimize these objects.

The global object is different, since it can be, and typically is,
visible to the javascript code.

> Since its properties are accessible without a suffix, i.e. global,
> It'd be tempting to think of it as a part of the window.document
> object.

Quite the opposite.

One of the properties of the global object in browsers has the name
"window". That is why you can write "window" directly in Javascript -
it is a global variable, i.e., a property of the global object.

The value of the "window" property is a reference to an object. It
is in fact a reference to the global object itself. So is the "self"
property, and in some cases also "parent" and "top". The global object
would survive, even if you changed what all these references points
to.

> Or are global objects not bound to the window.document
> object either - are only objects created with "var blahblah" or
> "self.blahblah" bound to window.document?

The global object is the base scope for for javascript executed as a
"Program" (as opposed to a "function body" or "eval block"). That
means that top-level variable declarations end up in the global
object, just like local variable declarations of function bodies end
up in the variable object of the function application. Ditto for
function declarations.

If you write
x=y;
and neither are declared as local or global variables, then you get an
error. When no variables are declared, the "y" is checked in the global
object, and it doesn't exist, so you can't find its value. That is an error.

You could write "window.y" which would merely give "undefined", because
that is property access, not variable lookup, even though the resulting
property would be the same.

If "y" was defined, but "x" wasn't, then "x" would also be searched
for in the global object. However, it is not an error that it is
undefined, since we don't attempt to read it. Instead a new property
called "x" of the global object is created, and the value of "y" is
stored in it.

> With frames, for example, I can access global variables in another
> frame via the document path.

That is correct. The global objects of one execution context might be
accessible as a normal object in another execution context. That
doesn't change that each execution has only one global object.

When javascript code is evaluated, the global object is the "window"
object (or really the opposite: the "window" object is the global
object) of the window from which the code was called.

Daniel

unread,
Jul 4, 2003, 8:36:47 AM7/4/03
to

"Richard Cornford" <Ric...@litotes.demon.co.uk> wrote in message
news:be2ndm$4t1$1$8300...@news.demon.co.uk...

> Ops, that's my fault. If you look closely at the way I have spelled
> function you will notice that the t and the i have been transposed. One
> of the hazards of touch typing into a word processor instead of a
> syntax-highlighting text editor. Though I am surprised that I did not
> notice Word complaining about the spelling, but there is a tendency to
> ignore highlighted spelling mistakes when entering code in Word. Sorry
> if that was confusion, correct the spelling an it will work as
> advertised.

No, actually it's my fault ;) I did see the typo and fixed it (I usually
write "functino" myself), but I called it using "new" which was obviously a
mistake.

> My reason for stressing that the assignment operation had a left hand
> side (var MyObject) and a right hand side (all the rest of the
> statement) was to try and explain how MyObject was only ever assigned
> the end result of the right hand side. There is not "hijacking" because
> the only value that is ever associated with the MyObject variable is a
> reference to a function object that was originally created as the inner
> function "constructor" within the execution context of the one-off
> function execution.

And that's *almost* how I saw it. I didn't see a sequence of assignments
going on, but a sequence of evaluations, with one final assignment. I simply
needed to visualize the "intermediate results" to properly conceive the
sequence and the final effect :P I just couldn't see that the Mr. One-Off
and his trail of closure came into play at the moment of assigning MyObject
its value. I wanted Mr. One-Off to come along for the ride =)

In other words, the final knot I needed to tie (should've been the first
knot) was that after something like this -

var blahblah = function() {
constructor = function() {
};
return constructor;

}();

- blahblah already holds the reference to constructor, and I wanted it to
hold a reference to the function expression until blahblah was called for
the first time. Which is also why the hijacking term was not only confusing
but plain out wrong - there's no reference to hijack =)

I also think that I held on to that illusion so long because I couldn't see
anything functionally proving it to be false, the difference between
illusion and fact was essentially the point of time the anonymous function
was "evaluated" or "executed", and delaying the evaluation demanded that a
ficticious reference to the function expression had to exist. If such a
reference did indeed exist, and it worked the way I wanted it too, I don't
think it would've caused any programmatical problems (at least not in this
context), it would probably just require a rewrite of the Javascript
specifications ;)

The facts are much more logic and easier to understand - it's kinda funny
(or, very irritating ;) that I didn't see them the first time.

> You seem to be seeing too much happening at once and Lasse is right,
> parenthesising the original statement should make the real sequence of
> events clearer.

Which is also what you say here =)

And here:

> At the point of executing:-
>
> var objectInstance = MyObject();
>
> - the MyObject variable already contains a reference to the inner
> function that was defined with the name "constructor". The one-off
> function has already been executed and done its work, At this point The
> one-off function has no accessible references and will never be executed
> again.

...

> The template for an ECMA Script object is much more loosely defined, and
> it is also mutable (though you wouldn't often want to do that). If my

Don't want to start another long thread that should have its own topic, but
what's "mutable"?

> original class was defined in the more traditional JavaScript way, as a
> separate constructor function and as properties of that function and its
> prototype object (the private members must now be public members as
> there are no closures to contain them), the results would look like:-
>
> function MyObject(){
> this.id = id;
> this.self = this; //pointless in an object with no inner functions
> this.index = MyObject.incrementCounter();
> }
> MyObject.prototype.getIndex = function(){
> return this.index;
> }
> MyObject.counter = 0;
> MyObject.incrementCounter = function(){
> MyObject.counter++;
> }
> MyObject.getNoOfInsts = function(){
> return counter;
> }
> MyObject.prototype.getId = function(){
> return this.id;
> }

It's really nice to see it like this, very familiar =)

> >Man, I really want the next words you say to be, "Actually I think
> >you *do* get it, Daniel, but for God's sake, man, work on your
> >ability to precisely explain what you mean!"
>
> Sorry, I am not going to say that until I can see that you have
> understood the behaviour of the in-line one-off function call. You are
> getting close and Lasse has posted a very explicit description so I am
> confident that you will have it under your belt next time.

How about now? =)

> As far as precise explanations, that goes both ways. If I was better at
> explaining then you might find understanding easier. Seeing where I fail
> to get my point across helps me to refine my explanation, which makes
> this whole exchange worthwhile in itself. I think that you are doing
> your half of the conversation very well. In describing your
> understanding at every stage I think that I can see which aspects of the
> process I am failing to properly convey.

Good to hear this is not just to my benifit. =)

> > If nothing else, I truly understand why
> >
> > alert(function(){ return function() { return true; }}()());
> >
> > Gives me an alert box with "true" written in it.
>
> Excellent! One more small step and your there.

Actually, when I said I understood that, I must have been either lying or
already "there" but too daft to realize it, because if I truly understood
that as I understood (read: misunderstood) the real issue, then I would have
had to believe that the alert box would write out "function" (at least if
suffixed by a typeof), since that would have been the "reference to hijack"
according to my illusion! Or maybe I just had to connect the simple with the
advanced :)

At least now, I TRULY truly understand it ;)

Thank you, both of you!

Daniel

Daniel

unread,
Jul 4, 2003, 9:25:35 AM7/4/03
to

"Lasse Reichstein Nielsen" <l...@hotpop.com> wrote in message
news:isqi4g...@hotpop.com...

> > What purpose could this global object serve?
>
> The global object is the repository of global variables. As such, it is
> effectively the top of all scope chains, so it is always in scope. That
> is what makes global variables possible at all.

Oooookayyy... When you wrote -

> function foo(x) {
> this.n=x;
> }
>
> foo(37); /* sets this.n = 37 with this == global object */

- I read foo as "becoming a global object", but ofcourse, since foo is
called without "new", there's no object instantiation, foo acts as a
function only, and "this" references *the* global object. Sloppy me! =)

> > Since its properties are accessible without a suffix, i.e. global,
> > It'd be tempting to think of it as a part of the window.document
> > object.
>
> Quite the opposite.

< ... >


> The value of the "window" property is a reference to an object. It
> is in fact a reference to the global object itself. So is the "self"
> property, and in some cases also "parent" and "top". The global object
> would survive, even if you changed what all these references points
> to.

Ah, this explains why global object values are accessible from other frames
with path dot notation AND locally without, since that's how any other
object works.

Thanks for this, I've really learned alot these few days =) This shouldn't
be called a newsgroup, it should be a class-is-in-session-group ;)

I think I'm about ready for a nice, long weekend =)


Daniel

Richard Cornford

unread,
Jul 4, 2003, 2:29:37 PM7/4/03
to
"Daniel" <sorry-n...@i-get-virus-and-spam.com> wrote in message
news:3f0574e1$0$97272$edfa...@dread12.news.tele.dk...
<snip>

>>The template for an ECMA Script object is much more loosely
>>defined, and it is also mutable (though you wouldn't often
>>want to do that). ...

>Don't want to start another long thread that should have its
>own topic, but what's "mutable"?

The opposite of immutable (which will be in your dictionary and means:
unchanging, unalterable, ageless.). Consider:-

function TestObject(){
this.getIndex = getIndex_TO;
}

TestObject.prototype.index = 0;

TestObject.prototype.incIndex = function(){
this.index = this.index + 1;
}

var getIndex_TO = function(){
return this.index + 1;
}

- if you created 50 objects with that constructor they would all be
created with the same template and exhibit the same behaviour. But if
you then executed:-

getIndex_TO = function(){
return this.index * 4;
}

- the next 50 objects would behave differently from the first 50. With
Java all objects of the same Class are created with the same code but in
JavaScript it is possible to make all sorts of changes to the code that
can be used to define a new object while your program is executing.

It would be reasonable to say that the first 50 TestObject instances are
not the same "Class" as the next 50, or to say that the "Class" has
changed. It is more likely the case that if you don't treat your object
defining code as immutable then the whole "Class" concept does not
really fit in with JavaScript at all.

Under the vast majority of circumstances modifying the code that will be
used to define a new Object of a particular "Class" is not something
that you would want to do. So "Class" as a concept will fit with
JavaScript. On the other hand, being able to modify it introduces some
interesting and potentially useful possibilities. Consider executing:-

var a = new TestObject();
var b = new TestObject();
a.incIndex();
TestObject.prototype.index = 5;
var c = new TestObject();
alert('a.index = '+a.index+
' b.index = '+b.index+
' c.index = '+c.index)

- with the original TestObject code. When initially reading the -
this.index - value the objects are reading the value from their
prototype. When the - incIndex - method increments the index it will set
a property of the object with the name "index" (masking the value on the
prototype). So changes to the value on the prototype impact upon objects
created before the change was made, but only if they have not already
executed their - incIndex - method and cut themselves of from reading
the value on the prototype.

Of course it is not going to be easy to usefully exploit the fact that
JavaScript offers that level of flexibility.

<snip>


>>>Man, I really want the next words you say to be, "Actually I
>>>think you *do* get it, Daniel, but for God's sake, man,
>>>work on your ability to precisely explain what you mean!"
>>
>>Sorry, I am not going to say that until I can see that you
>>have understood the behaviour of the in-line one-off function
>>call. You are getting close and Lasse has posted a very
>>explicit description so I am confident that you will have it
>>under your belt next time.
>
> How about now? =)

yes I actually do think that you get it. :)

<snip>
>>.. I think that I can see which aspects of the


>>process I am failing to properly convey.
>
>Good to hear this is not just to my benifit. =)

There is very little that appears altruistic that is not in reality at
least slightly selfish. During this exchange I have clarified various
details of the process of creating private static members in JavaScript
and improved my ability to explain it clearly. I have also had one of my
misconceptions corrected (thank you Lasse :). Lasse has also sparked a
completely new idea in my mind (that I will be responding to later).

<snip>


> Thank you, both of you!

You are welcome.

Richard Cornford

unread,
Jul 4, 2003, 9:23:16 PM7/4/03
to
"Lasse Reichstein Nielsen" <l...@hotpop.com> wrote in message
news:el17io...@hotpop.com...
<snip>

>I sometimes wish there was a clone method on all
>objects, but one can make it oneself:
>
> Object.prototype.clone = function () {
> function myConstructor = function(){};
> myConstructor.prototype = this;
> return new myConstructor();
> }
<snip>

I like the idea for being able to easily clone objects but I would
define a clone along the lines of a copy of a snapshot of an object at
the instant it was cloned. This clone method does not do that in fact
its behaviour is much more interesting.

Creating object A as - {x:1} - and then calling - var B = A.clone(); -
gives a clone of A which, if queried for its - x - property, will read
the property from its prototype (object A), so B.x == 1. However,
setting - A.x = 2 - and then reading B.x will give 2 because 2 is now
the value of the - x - property on B's prototype. Of course if - B.x -
is set then the property will be created locally on the object and it
will no longer be read from the prototype and so no longer reflect
changes made to that property on A.

That makes B more of a "live" copy of A as it will initially reflect the
current property values of A but slowly diverge as its own properties
are set and mask out those on its prototype.

Objects that exploited Douglas Crockford's closure based technique to
create private instance members would also produce some odd effects with
this code. Calling one of Douglas's "privileged" methods on a clone may
alter the clone by using the - this - keyword while still interacting
with the private members of the object that was cloned.

While mulling over the possibilities for exploiting these two new and
interesting object structures it dawned on me that there is a second
method of providing private static members in JavaScript. My first
method worked because all objects created with a constructor shared the
same constructor function and so could share the same closure formed
this that constructor. But equally all objects created with a
constructor also share that constructor function's prototype. So a
closure formed with the prototype cold also serve as a repository for
private static members. Something like:-

function MyObject(v){
this.value = v;
}
MyObject.prototype = function(proto){
var scale = 2; //private static method.
proto.getScaledValue = function(){//instance method with
// access to scale
return this.value * scale;
}
return proto;
}(MyObject.prototype);

Though the constructor and its inner functions would be denied access to
those private static members. That would not always matter but I think I
would generally prefer to form the closure with the constructor to
achieve private static members in JavaScript.

Richard.


Daniel

unread,
Jul 5, 2003, 11:05:07 AM7/5/03
to

> >Don't want to start another long thread that should have its
> >own topic, but what's "mutable"?
>
> The opposite of immutable (which will be in your dictionary and means:
> unchanging, unalterable, ageless.). Consider:-
>
<code & explanations>

This is actually the object behaviour I know from Actionscript (although I
didn't understand it as thoroughly before this thread), so I'm really glad
to see it's the same behaviour :)

> > How about now? =)
>
> yes I actually do think that you get it. :)

YAY! :P

Good to have my weekend with that one over :)

Have a good one!

0 new messages