class定義私有屬性和私有方法

2021-09-05 12:16:56 字數 828 閱讀 2453

私有方法和私有屬性,是只能在類的內部訪問的方法和屬性,外部不能訪問。

但 es6 不提供,只能通過變通方法模擬實現

下面是私有方法和私有屬性暴露的例子

class foo 

//私有方法

_bar(baz)

} const instance = new foo();

instance.foo(1);

instance.baz; //1

instance._bar(2); //2

instance.baz; //2

解決方案一

將私有方法移出模組,因為模組內部的所有方法都是對外可見的

class foo 

} function _bar(baz)

const instance = new foo();

instance.foo(1);

instance; //

instance._bar(); //uncaught typeerror: instance1.bar is not a function

解決方法二

利用symbol值的唯一性,將私有方法的名字命名為乙個symbol值,導致第三方無法獲取到它們,因此達到了私有方法和私有屬性的效果。

const bar = symbol('bar');

const baz = symbol('baz');

export default class foo

//私有方法

[bar](baz)

}

私有屬性和私有方法

應用場景及定義方式 應用場景 在實際開發中,物件的某些屬性或方法可能只希望在物件的內部使用,而不希望在外部被訪問到 私有屬性 就是 物件 不希望公開的 屬性 私有方法 就是 方法 不希望公開的 方法 定義方法 在定義屬性或方法時,在屬性名或者方法名前增加兩個下劃線,定義的就是私有屬性或方法 clas...

私有屬性和私有方法

應用場景 定義方式 不要問女生的年齡 self.age 18 def secret self print 我的年齡是 d self.age xiaofang women 小芳 私有屬性,外部不能直接訪問 print xiaofang.age 私有方法,外部不能直接呼叫 xiaofang.secret...

私有屬性和私有方法

class student object def init self,name,score 前面帶兩個下劃線表示對變數進行私有化 外部不能隨便的訪問和更改 self.name name self.score score defget grand self print my name is s,my ...