- 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.
> - 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.
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)
"Daniel" <sorry-no-em...@i-get-virus-and-spam.com> writes: > I have an object which contains a method that should execute every x ms. I > can use setInterval inside the object construct like this -
> - 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.
> 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!
> 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.
> 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 :)
"Daniel" <sorry-no-em...@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.)
> > 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.
> 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.
> 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
-- There are 10 kinds of people: Those who know binary and those who don't.
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.
>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.
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.
"Daniel" <sorry-no-em...@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 ;).
> 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
-- There are 10 kinds of people: Those who know binary and those who don't.
> 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 =)
-- There are 10 kinds of people: Those who know binary and those who don't.
"Daniel" <sorry-no-em...@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 =)
> 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
-- There are 10 kinds of people: Those who know binary and those who don't.
>... , 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();
//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
> 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?
-- There are 10 kinds of people: Those who know binary and those who don't.
>> 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?
>>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 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!
-- There are 10 kinds of people: Those who know binary and those who don't.