## 可見性 (私有域和保護域)
推薦使用 JSDoc 中的兩個標記: `@private` 和 `@protected`
JSDoc 的兩個標記 `@private` 和 `@protected` 用來指明類, 函數, 屬性的可見性域.
標記為 `@private` 的全局變量和函數, 表示它們只能在當前文件中訪問.
標記為 `@private` 的構造器, 表示該類只能在當前文件或是其靜態/普通成員中實例化; 私有構造器的公共靜態屬性在當前文件的任何地方都可訪問, 通過 `instanceof` 操作符也可.
永遠不要為 全局變量, 函數, 構造器加 `@protected` 標記.
```
// File 1.
// AA_PrivateClass_ and AA_init_ are accessible because they are global
// and in the same file.
/**
* @private
* @constructor
*/
AA_PrivateClass_ = function() {
};
/** @private */
function AA_init_() {
return new AA_PrivateClass_();
}
AA_init_();
```
標記為 `@private` 的屬性, 在當前文件中可訪問它; 如果是類屬性私有, “擁有”該屬性的類的所有靜態/普通成員也可訪問, 但它們不能被不同文件中的子類訪問或覆蓋.
標記為 `@protected` 的屬性, 在當前文件中可訪問它, 如果是類屬性保護, 那么”擁有”該屬性的類及其子類中的所有靜態/普通成員也可訪問.
注意: 這與 C++, Java 中的私有和保護不同, 它們是在當前文件中, 檢查是否具有訪問私有/保護屬性的權限, 有權限即可訪問, 而不是只能在同一個類或類層次上.而 C++ 中的私有屬性不能被子類覆蓋.
(C++/Java 中的私有/保護是指作用域上的可訪問性, 在可訪問性上的限制. JS 中是在限制在作用域上. PS: 可見性是與作用域對應)
```
// File 1.
/** @constructor */
AA_PublicClass = function() {
};
/** @private */
AA_PublicClass.staticPrivateProp_ = 1;
/** @private */
AA_PublicClass.prototype.privateProp_ = 2;
/** @protected */
AA_PublicClass.staticProtectedProp = 31;
/** @protected */
AA_PublicClass.prototype.protectedProp = 4;
// File 2.
/**
* @return {number} The number of ducks we've arranged in a row.
*/
AA_PublicClass.prototype.method = function() {
// Legal accesses of these two properties.
return this.privateProp_ + AA_PublicClass.staticPrivateProp_;
};
// File 3.
/**
* @constructor
* @extends {AA_PublicClass}
*/
AA_SubClass = function() {
// Legal access of a protected static property.
AA_PublicClass.staticProtectedProp = this.method();
};
goog.inherits(AA_SubClass, AA_PublicClass);
/**
* @return {number} The number of ducks we've arranged in a row.
*/
AA_SubClass.prototype.method = function() {
// Legal access of a protected instance property.
return this.protectedProp;
};
```