`protected` vs `private`
private
標識為private
的屬性為私有屬性,不能在除自己外的地方進行訪問。
protected
標識為protected
的屬性為受保護的屬性,與私有屬性類似,但還可以在繼承類中進行訪問。
示例
以 TypeScript 為例,比如一個Base
類,其中包含一個受保護的年齡屬性age
,以及一個私有的工資_salary
屬性。
class Base { constructor(protected age: number, private _salary: number) {} }
同時定義一個Derived
類繼承自Base
類:
class Derived extends Base { constructor(public name: string, age, salary) { super(age, salary); } get Age() { // :white_check_mark: 保護的屬性可以從繼承類中獲取到 return this.age; } get Salary() { // :rotating_light: Property '_salary' is private and only accessible within class 'Base'.ts(2341) return this._salary; } }
然後分別例項化這兩個類:
const base = new Base(18, 999); const derived = new Derived("derived", 20, 1000);
然後通過他們的例項嘗試訪問這些屬性。
// :rotating_light:Property '_salary' is private and only accessible within class 'Base'.ts(2341) console.log(base._salary); // :rotating_light:Property 'age' is protected and only accessible within class 'Base' and its subclasses.ts(2445) console.log(base.age);
對於base
,其兩個屬性都無法通過例項進行訪問。
// :white_check_mark: console.log(derived.name); // :rotating_light: 雖然繼承類中可以獲取到父類的保護屬性,但不能通過例項直接進行訪問 console.log(derived.age); // :white_check_mark: 只能在繼承類的例項方法中訪問,這裡 `Age` 是繼承類提供的獲取器,該方法裡訪問並返回了父類的保護屬性 `age` console.log(derived.Age);
對於derived
,其中name
因為是public
公有的,所以可通過例項直接訪問。
age
繼承自父類Base
,只能在Derived
類中的例項方法,比如這裡定義的get Age
獲取器中進行訪問。但無法通過Derived
的例項直接訪問。
Age
在這裡為Derived
類上面的一個獲取器,其預設有public
屬性,通過訪問它我們間接在類外面訪問到了這個在父類中標識為受保護的屬性age
。