【发布时间】:2013-11-13 17:08:25
【问题描述】:
我有以下 JavaScript Object Literal Notation 对象
var Parameters= {
modal_window:{
backdrop:true,
keyboard:true,
show:true,
remote:false,
type:{
normal:function(){
this.footer.button.accept.type='btn btn-primary';
this.header.type='modal-header';
},
success:function(){
this.footer.button.accept.type='btn btn-success';
this.header.type='modal-header alert alert-success';
},
info:function(){
this.footer.button.accept.type='btn btn-info';
this.header.type='modal-header alert alert-info';
},
error:function(){
this.footer.button.accept.type='btn btn-danger';
this.header.type='modal-header alert alert-error';
},
warning:function(){
this.footer.button.accept.type='btn btn-warning';
this.header.type='modal-header alert';
}
}
},
header:{
title:undefined,
type:this.window.type.normal.header
},
footer:{
button:
{
accept:{
title:'Accept',
click:undefined,
type:undefined
},
cancel:{
title:'Cancel',
click:undefined
}
}
}
};
是否可以让header.type和footer.button.accept.type只读变量只能通过window.type.normal、window.type.success等来改变?
说明: 我想在这里做一些澄清。我的Parameters.header.type 应该是只读的并且应该有默认值。而当用户 选择例如Parameters.modal_window.type.normal 必须更改Parameters.header.type。
【问题讨论】:
-
不,在 javascript 中只读是不可能的。
-
只读可以使用
Object.defineProperty,或者我使用带有闭包的函数。 -
好吧,如果您的代码有意义,我会这样做,但是当 this.window.type.normal.header 被调用时,
this是全局上下文(窗口)。 -
还有一件事,这是一个原型设计模式?
-
@andy 我认为这实际上在现代 JavaScript 运行时是可能的(支持 getter/setter)。
标签: javascript