Gregory Hill wrote:
Imagine the situation, when loop body removes one element from the
array. It's quite common situation, for example when you operate on
select tag and remove options dynamically in loop body, in each loop
pass. Thus the length of option collection has changed, and the
length must be recalculated.
It makes sense, but I was curious how it is possible, given the fact
that in Javascript when you access something as an attribute, it doesn't
behave as a function. For example, say you were to create your own
object with a .length attribute. Could you recalculate that on the fly?
No, unless you defined it as a function and then you'd have to call it
as a function (this.length() instead of this.length). (Or is it
possible by some means I am unaware of?)
In may programming languages there is a concept of getters and setters, that are
functions that run when a "property" is accessed or set. The length property of
an Array object is an example of a getter.
Pretty sure that it's not cross browser compatible (not IE, but FF1.5 in my
testing), but actually you can define getters and setters that behave within
your code as if they are properties, but they are actually functions/methods.
Here's a quick page that describes this concept a little:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters
and also a little more here:
http://ajaxian.com/archives/2005/11/getters_and_set.html
Probably more link via google
So, changing the behavior for
built-ins opens up a large can of worms for programming errors. When
you call array.length, you expect it to just retrieve a value. If it
were a function, array.length(), you'd expect it to be more intensive
and you would be more likely to store the value locally. It's
inconsistent, and troublesome, given the fact that there could be myriad
other similar examples. Anyway, I guess it just annoys me that this is
possible because it means I probably have a lot of optimizing I could do
that wouldn't have been an issue if they'd made the built-ins behave the
same as user-defined objects.
Anytime you access a variable's property multiple times, as in a for loop it takes longer
to access it via obj.property then to use var p = obj.property and then use p wherever
you needed the value. This presumes that the value of p doesn't change over the course of
the operations you're performing, or you need to "recalculate" it every time
you change it, or just access the property directly each time and live with the extra
time it takes.
--
Danilo Celic
| Extending Knowledge Daily : http://CommunityMX.com/
| Team Macromedia for Dreamweaver : http://macromedia.com/go/team/
_______________________________________________
Rails-spinoffs mailing list
Rails-spinoffs@lists.rubyonrails.org
http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs