Chào mọi người,
Mọi người cho em hỏi là việc var có thể được re-declaration nhằm mục đích gì vậy ạ? Nó có chức năng cụ thể khi mà ta làm vậy hay là chỉ là 1 đặc điểm của var khác với let?
Em cảm ơn.
Chào mọi người,
Mọi người cho em hỏi là việc var có thể được re-declaration nhằm mục đích gì vậy ạ? Nó có chức năng cụ thể khi mà ta làm vậy hay là chỉ là 1 đặc điểm của var khác với let?
Em cảm ơn.
var không phải kiểu dữ liệu đâu bạn
Đây là JS, không phải C hay C++.
JavaScript has three kinds of variable declarations.
var
Declares a variable, optionally initializing it to a value.
let
Declares a block-scoped, local variable, optionally initializing it to a value.
const
Declares a block-scoped, read-only named constant.
Mình thử tìm kiếm với từ khoá can var be redeclared và đã tìm thấy vài thông tin hay ho.
Có 1 ví dụ thực tế rất hay:
var _gaq = _gaq || [];In other words, if
_gaqis already defined,_gaqis “redeclared” as itself. If it is not defined, it will be declared for the first time as an empty array.[…]
Redeclaring a variable is useful in situations where it cannot be known if the variable has already been defined.
By redeclaring a variable conditionally, as Google Analytics tracking code does, it allows for a variable to safely originate from more than one place.
In this example it could be safe for other code using the
_gaqvariable to likewise check for a predefined_gaqvariable. If it exists, it knows it can use it. If it doesn’t exist, it knows that it should define it before trying to use it.
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?