Home  >  Article  >  Backend Development  >  javascript - Why are JS private variables inaccessible?

javascript - Why are JS private variables inaccessible?

WBOY
WBOYOriginal
2016-08-23 09:17:431106browse

<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?

Reply content:

<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?


This is not a private property at all. This is just a variable you declare inside the function. Since it is an attribute, you also know whether an attribute is private or not. Therefore, the attribute itself has a question of "who does it belong to?" Do you understand what I mean? If you change the constructor to this.risk=0; you will find that you can find it. This is the owner of the attribute here.

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.

You mentioned private attributes. Can it still be called private if it can be accessed?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn