Calling an object property from within a variable vs outside a variable (JS)

五迷三道 提交于 2019-12-11 21:13:24

问题


Whats the difference between the two calls? It almost seems identical but running it tells me otherwise. Calling the property from within the variable, and outside the variable seem to be calling different things but I'm not sure how or why.

PS. Cheese is a boolean property set to false.

  toggleCheese: function(position) {
    var pizza = this.pizza[position].cheese;
    pizza = !pizza;

}

vs

  toggleCheese: function(position) {
    var pizza= this.pizza[position];
    pizza.cheese = !pizza.cheese;

}


回答1:


Let’s cut this down to the important parts. Say you have an object representing a very simple pizza,
{ cheese: false }. We’ll make a variable pizza and point it at the object:

var pizza = { cheese: false };

then make another variable cheese and point it at the value of the object’s cheese property:

var cheese = pizza.cheese;

Now, the difference between these two:

cheese = true;
pizza.cheese = true;

is that the former means “point the variable cheese to true” and the latter means “take the value the variable pizza points at, and point its cheese property to true”. One only affects the cheese variable, and the other affects the pizza object like you want. In other words, these are really two unrelated forms of the assignment operation:

<variable> = <value>;
<value>.<property> = <value>;

If you want to set a variable, use the variable form; if you want to set a property, use the property form.



来源:https://stackoverflow.com/questions/51460719/calling-an-object-property-from-within-a-variable-vs-outside-a-variable-js

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