Home > Article > Backend Development > javascript - Why are JS private variables inaccessible?
<code>function Customer(name) { var risk = 0; this.name = name; } var customer = new Customer("aa"); console.log(customer.name); // aa console.log(customer.risk); // undefined </code>
Excuse me, why is customer.risk inaccessible but customer.name is accessible? Whose private variable is risk? Is it customer's? If so, why can't customer access his own private variable?
<code>function Customer(name) { var risk = 0; this.name = name; } var customer = new Customer("aa"); console.log(customer.name); // aa console.log(customer.risk); // undefined </code>
How could you accept such an answer?
In the function constructor, use
var
to declare a variable. This variable can be considered private. If it is not exposed through a closure or similar method, it will not be accessible from the outside. Moreover, risk
is not a private variable of customer
. It has nothing to do with customer
, but is related to the function object Customer
. Using the
new
operator will return an object, and the this
of the called function constructor will point to the object to be returned, so the properties you declare using this
can be accessed by the object returned by new
. This is somewhat similar to a closure, except that the closure is a function, here it is an object.