What's the difference between a boolean as primitive and a boolean as property of an object?

I'm following some canvas tutorial. The code below is a snippet of that.

In this snippet, why would they not choose for runAnimation to be a simple boolean? I would think the x = !x statement would work anyways, but when i tried changing the code to use booleans, the code didn't work.

So, what's the difference between a boolean as primitive and a boolean as property of an object?

   /*
   * 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;

All arguments are passed by "value" in JavaScript. This means that when an argument is passed, a copy of what's stored in the variable is passed.

Primitives (like booleans) store the actual data they represent and so, when a primitive is passed, a copy of the data is sent, resulting in two copies of the data. Changes to one, won't affect the other.

But, when you assign an object to a variable, the variable stores the memory location for where that object can be found, not the object itself. Passing an object as an argument results in a copy of the memory address being passed. In these cases, you may wind up with two variables that store the same memory address, so no matter which variable you use, the same one underlying object is affected.

In your scenario, you could certainly make it work with just a boolean variable, but it appears that the tutorial wants to encapsulate that into an object so that copies of the boolean data won't be floating around and there will be less chances of accidentally changing one variable but not another.

Here's some basic examples:

// 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);
链接地址: http://www.djcxy.com/p/3534.html

上一篇: ECMAScript中定义的对象的可变性在哪里?

下一篇: 作为一个对象的属性,布尔为原始类型和布尔值之间的区别是什么?