创建支持公共和私有属性的对象的好方法是使用工厂函数:
function createObj(){
var privateVariable = "private";
var result = {};
result.publicProp = 12;
result.publicMethod = function() {
alert(this.publicProp);
alert(privateVariable);
};
//this will add properties dynamically to the object in question
result.createProperty = function (name, value) {
this[name] = value;
};
return result;
}
Run Code Online (Sandbox Code Playgroud)
至于静态,你可以通过将它们放在函数本身上来模拟它们
createObj.staticProperty1 = "sorta static";
Run Code Online (Sandbox Code Playgroud)
并查看动态属性:
var obj = createObj();
obj.createProperty("foo", "bar");
alert(obj.foo); //alerts bar
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
515 次 |
| 最近记录: |