Immutable primitive types
Why can't the following argument be made against the claim that primiti开发者_如何学Pythonve types are immutable in Javascript:
var $b = false;
$b = true;
alert($b); //-> true
I am misunderstanding what it means for a variable to immutable.
Values are immutable; variables are not.
$b = true
changes $b
to contain the true
value.
The immutable false
value is not changed.
Some languages support immutable variables as well (C++'s const
, Java's final
, or C#'s readonly
); Javascript does not.
An immutable variable is one that can't be changed, like a constant. Unfortunately, there are no true immutable variables in JavaScript (at least that I am aware of).
The closest you can get is by using a closure with a getter method.
Scope is mutable, true
and false
are not.
You just showed that scope is mutable, and nothing about whether or not true
or false
are mutable.
精彩评论