Javascript multiple asignment re-evaluation or result passing?

好久不见. 提交于 2020-01-06 03:18:04

问题


The multiple assignment (or is it called chaining?) that I'm talking about is assignment such as:

a = b = c = 2;

...after which a, b, and c are all equal to 2;

My question of optimization is, given the following code:

var dom1 = document.getElementById('layout_logos');
var dom2 = document.getElementById('layout_sitenav');
...
function layout_onscroll(){
  ...
  dom1.style.height = dom2.style.top = maxLogoHeight - scrollTop;
  ...
}

From what I've been reading, I'm afraid the code in layout_onscroll is evaluating to:

dom2.style.top = maxLogoHeight - scrollTop;
dom1.style.height = dom2.style.top;

.. which gives the right value but accesses dom2 twice -- once to set top and once to get top. (note I'm coming from a .NET background where Microsoft wraps everything in layers upon layers of accessor functions making loops using those buried variables prohibitively slow.)

If so, is it faster to create an additional variable and then assign both DOM elements to that variable?

  ...
  var temp_var = maxLogoHeight - scrollTop;
  dom1.style.height = temp_var;
  dom2.style.top = temp_var;
  ...

The obvious loss doing that comes from allocating the temp var every time. But if dom2.style.top is accessed by two getter functions under the hood (e.g. if the first version calls dom2.getStyle().getTop() which in turn parses all the text of dom2's css for the word 'top') then allocating a temp var may be faster.


回答1:


This:

dom1.style.height = dom2.style.top = maxLogoHeight - scrollTop;

… is not quite the same as this:

dom2.style.top = maxLogoHeight - scrollTop;
dom1.style.height = dom2.style.top;

Instead, the right-hand operand maxLogoHeight - scrollTop is assigned to each of dom1.style.height and dom2.style.top.

We can see this in the following example:

Snippet

var d= document.getElementById('D');

s = d.style.width= 'abc';
console.log(s);             //'abc'

d.style.width= 'abc';
s= d.style.width;
console.log(s);             //null string
#D {height: 100px; width: 100px; background: red;}
<div id="D"></div>

abc is an invalid width, and it is therefore discarded by d.style.width. However, you'll see that s is assigned abc in the first console.log(), and it's assigned the null string in the second console.log().


The following example may be more intuitive:

const x = 3;
var y = x = 6;                   // x cannot change.  So is y 3 or 6?
document.body.innerHTML= x + y;  // -> 9 ... y must be 6!


来源:https://stackoverflow.com/questions/31414129/javascript-multiple-asignment-re-evaluation-or-result-passing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!