问题描述
这两个调用有什么区别?它几乎看起来相同,但运行它告诉我不同.从变量内部和变量外部调用属性似乎是在调用不同的东西,但我不确定如何或为什么.
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.
附注.Cheese 是一个布尔属性,设置为 false.
PS. Cheese is a boolean property set to false.
toggleCheese: function(position) {
var pizza = this.pizza[position].cheese;
pizza = !pizza;
}
对比
toggleCheese: function(position) {
var pizza= this.pizza[position];
pizza.cheese = !pizza.cheese;
}
推荐答案
让我们将其分解为重要部分.假设您有一个表示非常简单的比萨饼的对象,{ cheese: false }
.我们将创建一个变量 pizza
并将其指向对象:
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 };
然后创建另一个变量 cheese
并将其指向对象的 cheese
属性的值:
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;
是前者的意思是将变量cheese
指向true
",后者的意思是取变量pizza
指向的值,并将其 cheese
属性指向 true
".一个只影响 cheese
变量,另一个影响你想要的披萨对象.换句话说,这实际上是两种不相关的赋值操作形式:
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.
这篇关于从变量内部调用对象属性与变量外部 (JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!