我正在关注一些 Canvas tutorial .下面的代码是其中的一个片段。
在这个片段中,他们为什么不选择 runAnimation
为简单的 bool 值?我认为 x = !x
语句无论如何都会起作用,但是当我尝试更改代码以使用 bool 值时,代码不起作用。
那么,作为对象的原始 bool 值和作为对象属性的 bool 值有什么区别?
/*
* define the runAnimation boolean as an object
* so that it can be modified by reference
*/
var runAnimation = {
value: false
};
// add click listener to canvas
document.getElementById('myCanvas').addEventListener('click', function() {
// flip flag
runAnimation.value = !runAnimation.value;
最佳答案
在 JavaScript 中,所有参数都是通过“值”传递的。这意味着当传递参数时,会传递存储在变量中的内容的副本。
基元(如 bool 值)存储它们代表的实际数据,因此,当传递基元时,会发送数据副本,从而产生两个副本数据。对一个的更改不会影响另一个。
但是,当您将对象分配给变量时,变量存储可以找到该对象的内存位置,而不是对象本身。将对象作为参数传递会导致传递内存地址的副本。在这些情况下,您可能会得到两个存储相同内存地址的变量,因此无论您使用哪个变量,都会影响同一个底层对象。
在你的场景中,你当然可以让它只使用一个 bool 变量,但教程似乎想将它封装到一个对象中,这样 bool 数据的副本就不会四处 float ,而且会更少意外更改一个变量而不更改另一个变量的可能性。
这里有一些基本的例子:
// This function takes a single argument, which it calls "input"
// This argument will be scoped to the function.
function foo(input){
// The function is going to alter the parameter it received
input = input + 77;
console.log(input);
}
var input = 100; // Here's a higher scoped variable also called "input"
foo(input); // We'll pass the higher scoped variable to the function
// Now, has the higher level scoped "input" been changed by the function?
console.log(input); // 100 <-- No, it hasn't because primitives pass a copy of their data
// ************************************************
// Now, we'll do roughly the same thing, but with objects, not primitives
function foo2(obj){
obj.someProp = 100;
console.log(obj.someProp);
}
var obj = {
someProp : 50
};
foo2(obj);
// Here, we see that the original object has been changed by the funciton we passed it to
console.log(obj.someProp);
关于javascript - 作为对象的原始 bool 值和作为对象属性的 bool 值有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42045586/