Using setInterval inside an object

D

Daniel

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
 
L

Lasse Reichstein Nielsen

Daniel said:
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.

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
 
D

Daniel

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
 
L

Lasse Reichstein Nielsen

Daniel said:
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::) )

/L
 
L

Lasse Reichstein Nielsen

Daniel said:
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.)

/L
 
R

rh

Lasse Reichstein Nielsen said:
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.

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
 
D

Daniel

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 =)
 
D

Daniel

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
 
D

Daniel

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
 
D

Daniel

Lasse Reichstein Nielsen said:
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 =)
 
D

Daniel

Lasse Reichstein Nielsen said:
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
 
R

Richard Cornford

... , 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.
 
D

Daniel

Daniel said:
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 ;)
 
R

Richard Cornford

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?
 
D

Daniel

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!
 
D

Daniel

Daniel said:
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 ;)
 
D

Daniel

Richard Cornford said:
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?
 
R

Richard Cornford

Daniel said:
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.

..., 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.
 
D

Daniel

Richard Cornford said:
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
 
L

Lasse Reichstein Nielsen

Daniel said:
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 :)

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top