javascript - 如果属性不是赋值语句的一部分,JavaScript 会计算属性的值吗?

标签 javascript browser cross-browser variables evaluation

我遇到了一个相当晦涩的问题,该问题与在浏览器应用样式之前测量文档的高度有关。更多信息在这里:

在 Dave Hyatt 6 月 27 日的评论中,他建议简单地检查 document.body.offsetLeft 属性以强制 Safari 进行重排。

我可以简单地使用以下语句吗:

document.body.offsetLeft;

或者我需要将它分配给一个变量,例如:

var force_layout = document.body.offsetLeft;

为了让浏览器计算那个值?

我认为这归结为一个更基本的问题 - 即,如果不作为赋值语句的一部分,JavaScript 是否仍会评估属性的值?这是否取决于特定浏览器的 JavaScript 引擎是否优化了代码?

最佳答案

该语句仍将被评估。

     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');
  }
});

注意:上面的示例适用于 IE9 Pre、Firefox 3.7alpha、Chrome 5 和 WebKit nightly builds。

然后一个简单的表达式作为您的示例,使 getter 调用:

obj.prop; // alerts "getter"

关于javascript - 如果属性不是赋值语句的一部分,JavaScript 会计算属性的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3008813/

相关文章:

php - 单击浏览器后退按钮获取用户选择

javascript - 用于跨浏览器事件支持的轻量级库

javascript - 在React Native中使用装饰器,找不到变量: require

javascript - 表单未通过 onclick 事件提交

silverlight - Silverlight 中的并发连接数

http - 为什么浏览器不遵循呈现的 GitHub README.md 上图像资源的 HTTP 302 重定向?

javascript - Firefox 与 IE/Chrome 中的事件处理程序

html - 独立于 <select> 调整 <option> 的大小

javascript - 自定义 HTML 属性,: Firefox vs. IE

javascript - 如何让这个div滑过半个屏幕?