在 javascript 中将变量赋给自身有什么隐藏的优势? "force reflow"?

Any hidden advantage of assigning a variable to itself in javascript? "force reflow"?

我正在对一个 js 代码库进行代码检查,我得到了一些分配给它们自己的变量。我在 ui-bootstrap-tpls-0.5.0.js:445 中发现了一个奇怪的赋值,它是:

nextSlide.$element[0].offsetWidth = nextSlide.$element[0].offsetWidth; //force reflow

注释 // force reflow 是什么意思?

总的来说,JS中变量自赋值有什么优势吗? DOM 个节点?

您可以在 Rendering: repaint, reflow/relayout, restyle

中阅读有关回流的更多信息

本质上,'reflow' 是在浏览器渲染模型中启动 'layout' 更新的东西。如果您知道发生了需要重新呈现页面的更改,但由于某种原因这可能没有发生,这将很有用。

关于什么可以或应该导致重排,或者何时实际重新计算布局的具体细节取决于每个浏览器的实现。来自上面链接的文章:

Since the reflows and repaints associated with render tree changes are expensive, the browsers aim at reducing the negative effects. [...]. The browser will setup a queue of the changes your scripts require and perform them in batches.

因此,您可能会发现您希望 reflow/layout 发生的情况,但浏览器布局批处理策略阻止了它(目前)发生。这似乎是原始代码试图解决的问题。

这种模式有时也用于刷新网页,例如:

// refresh the current web page 
document.location.href = document.location.href;

或用于重绘HTML5 canvas,例如:

// .. draw some pretty cool shapes here 
// force canvas to redraw
canvas.width = canvas.width;

希望对您有所帮助。