我使用以下代码创建:私有(private)属性、私有(private)方法、公共(public)属性、公共(public)方法和公共(public)静态属性。
function ClassA() {
var privateProperty = 'private_default_value';
var privateMethod = function() {
console.log("private method executed ...");
};
this.publicProperty = 'public_default_value';
this.publicMethod = function() {
console.log("public method executed ...");
};
ClassA.publicStaticProperty = "public_static_default_value";
// How to create here: ClassA.privateStaticProperty ?
};
var instance = new ClassA();
instance.publicMethod();
console.log(ClassA.publicStaticProperty);
如何在此类中创建私有(private)静态属性?
最佳答案
这是一个使用 IIFE 的解决方案创建构造函数可见的作用域 ClassA
:
var ClassA = (function(){
var Constructor = function(){
var privateProperty = "private_default_value";
var privateMethod = function() {
console.log("private method executed ...");
};
this.publicProperty = "public_default_value";
this.publicMethod = function() {
console.log("public method executed ...");
};
}
Constructor.publicStaticProperty = 'public_static_default_value';
var privateStaticProperty = "private_static_default_value";
return Constructor;
})();
privateStaticProperty
是“静态的”:只有一个属性。
privateStaticProperty
是“私有(private)的”:您无法从 IIFE 外部读取它。
关于javascript - 在 Javascript 中创建私有(private)静态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24452025/