Related learning recommendations: javascript video tutorial
Since its release, ES6 has brought some new features to JavaScript and methods. These features can better improve our workflow and productivity as JavaScript developers. These new features include the Object.freeze()
method and the const
.
Among a few developers, especially newbies, some people think that these two features work the same, but NO, they are not. Object.freeze()
and const
work differently. Let me show you how!
const
is completely different from Object.freeze()
.
const
behaves like let
. The only difference is that it defines variables that cannot be reassigned. const
Variables declared with var
are block-scoped, not function-scoped, like variables declared with
const<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const user = 'Bolaji Ayodeji'user = 'Joe Nash'复制代码</pre><div class="contentsignin">Copy after login</div></div>
This will raise Uncaught TypeError
because we are trying to reassign the key using const
Variables declared with the word
##Initially, this will work with
var or
let, but not
const
Consider the following code. We have declared a variable using the
const keyword and assigned it an object named
user
We absolutely want objects to have properties that cannot be modified or deleted.
const There's no way to do that, and that's where
Object.freeze()
To disable any changes to the object we need
Object.freeze()
Well,
Object.freeze()
So when
Object.freeze()
const
differs from
Object.freeze() in that
const prevents reallocation, while
Object.freeze()
###If you want to know more about programming learning, please pay attention to the php training
column!
The above is the detailed content of Understand the difference between Object.freeze() and const in JavaScript. For more information, please follow other related articles on the PHP Chinese website!