vote up 0 vote down
star

I'm just curious how this is done directly by browsers. I heard that .length property of Array in Javascript Engines in fact uses invisible setters and getters to achieve functionality of ECMA-s standard that says: "whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted"). I understand that setter is needed in this case, but what with getter? Do we really need to call native getter to get this value? Or this is only a some mistake with understanding Javascript Engine somewhere?

Thanks for any answers here :)

flag
add comment

4 Answers:

vote up 2 vote down
check

A property is either implemented as a field or as setter/getter methods.

If it's a field then it's just a value, when setting the value nothing more happens than that the value changes.

If you have a setter method in order to perform something more whenever the value is set, you also have a getter method to match, even if the getter method doesn't do anything more than just return the value. You don't want to mix the two ways of implementing a property, it's just a lot simpler to go all the way in either direction.

link|flag
add comment
vote up 2 vote down

Have a look at defineGetter and defineSetter. This might be how Firefox does it, but I'm not sure about the other browsers.

Does it really matter? .length could be implemented in c++ for all I know. It could be a builtin part of the javascript engine, and not really implementable in javascript in anyway. All that you, the user, needs to know is that the length holds the length of the array, and if you change it the length of the array changes.

link|flag
Native objects can have their own getters / setters. – Jason S Mar 5 at 14:16
add comment
vote up 1 vote down

For starters, the JavaScript Array object has a function property .length() which will return the current length of the array instance. Getters and setters can be defined in as of JavaScript 1.6 (I think) but it's not widely adopted and I haven't seen much use of it. The only difference between a getter and a function that returns a value is the syntax. Getters and setters can are called by the engine depending on direction of assignment.

var obj = {myProp:0}.myProp; // getting
obj.myProp = 1; // setting

The above example is a bit funky, but I think you get the idea...

link|flag
add comment
vote up 0 vote down

The ECMA specification does not define how the length property is implemented, merely how it behaves. The exact methods used almost certainly differ between browser vendors, and are irrelevant to you as an end-user.

link|flag
add comment

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.