views:

32

answers:

1

I've come across a fairly obscure problem having to do with measuring a document's height before the styling has been applied by the browser. More information here:

In Dave Hyatt's comment from June 27, he advises simply checking the document.body.offsetLeft property to force Safari to do a reflow.

Can I simply use the following statement:

document.body.offsetLeft;

or do I need to assign it to a variable, e.g.:

var force_layout = document.body.offsetLeft;

in order for browsers to calculate that value?

I think this comes down to a more fundamental question - that is, without being part of an assignment statement, will JavaScript still evaluate a property's value? Does this depend on whether a particular browser's JavaScript engine optimizes the code?

+2  A: 

The statement will still be evaluated.

     Property Accessors
            |    |
            v    v
    document.body.offsetLeft;
      ^
      |- Identifier Reference

In the above statement, you can see that document is a Identifier Reference, which is a Primary Expression.

Then the property accessor operator is used (.) too lookup the body property and then the offsetLeft property.

You are not doing an AssignmentExpression but the statement will be evaluated because the Identifier Reference is resolved, and the properties are looked up.

Also, host objects, can implement accessor properties that can have a logic get and set methods, not just simple value properties.

In ECMAScript 3, we didn't had the power of creating accessor properties, only the host objects could implement them, but the 5th Edition of the standard allows us to do it.

For example to illustrate:

var obj = {};
Object.defineProperty(obj, 'prop', { // ECMAScript 5 method
  get: function () {
    alert('getter');
  }
});

Note: The above illustrative example works on IE9 Pre, Firefox 3.7alpha, Chrome 5, and WebKit nightly builds.

Then a simple expression as your example, makes the getter to invoke:

obj.prop; // alerts "getter"
CMS
Great explanation! That makes sense. I had a hunch that that's what was happening, but I couldn't articulate it as such. Thanks so much, CMS!
Bungle