布尔作为基元和布尔作为对象的属性有什么区别?

Mar*_*sen 4 javascript html5-canvas

我正在关注一些画布教程.下面的代码是一个片段.

在这个片段中,他们为什么不选择runAnimation成为一个简单的布尔值?我认为该x = !x声明无论如何都会起作用,但是当我尝试更改代码以使用布尔时,代码不起作用.

那么,作为基元的布尔值和作为对象属性的布尔值之间的区别是什么?

   /*
   * 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;
Run Code Online (Sandbox Code Playgroud)

Sco*_*cus 7

所有参数都在JavaScript中通过"value"传递.这意味着当传递参数时,会传递存储在变量中的副本.

基元(如布尔值)存储它们所代表的实际数据,因此,当传递基元时,将发送数据的副本,从而产生两个数据副本.改变一个,不会影响另一个.

但是,当您将对象分配给变量时,该变量会存储可以找到该对象的位置的内存位置,而不是对象本身.将对象作为参数传递会导致传递的内存地址的副本.在这些情况下,您最终可能会使用两个存储相同内存地址的变量,因此无论您使用哪个变量,都会影响同一个基础对象.

在你的场景中,你当然可以使它只使用一个布尔变量,但似乎教程想要将它封装到一个对象中,这样布尔数据的副本就不会浮动,并且意外的机会也会减少改变一个变量但不改变另一个.

这是一些基本的例子:

// 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);
Run Code Online (Sandbox Code Playgroud)