JS中4个描述行为的键值
1.value 表示与属性有关的值
示例如下:
<script type="text/javascript">
var obj={}
Object.defineProperty(obj,'x',{
value:100
});
document.write(obj.x)
</script>
2.writable表示是否可改变值,默认为false
默认情况如下:
<script type="text/javascript">
var obj={}
Object.defineProperty(obj,'x',{
value:100
});
document.write(obj.x+'<br/>')
obj.x=123;
document.write(obj.x)
</script>
此时writable值默认为false,所以x没有被更改,
若在上述代码中加入writable:true
则效果如图:
3.enumerable表示是否可枚举,默认为false
代码及效果如下:
<script type="text/javascript">
var obj={}
Object.defineProperty(obj,'x',{
value:100,
writable:true,
enumerable:true,
});
for(p in obj){
document.write(p)
}//for-in 用来枚举元素
</script>
将上述代码中enumerable:true改为enumerable:false后得:
4.configurable表示是否可配置(配置包括删除属性值或改变writable、enumerable的值),默认为false
若为默认值,则:
<script type="text/javascript">
var obj={}
Object.defineProperty(obj,'x',{
value:'this is a test',
writable:true,
enumerable:true,
configurable:false,
});
obj.x='hhha'
document.write(obj.x+'<br/>');
delete obj.x;
document.write(obj.x);
</script>
将configurable:false改为configurable:true得:
若configurable的值为true还表示能更改writable、enumerable的值,代码如下:
<script type="text/javascript">
var obj={}
Object.defineProperty(obj,'x',{
value:'this is a test',
writable:true,
enumerable:true,
configurable:true,
});
Object.defineProperty(obj,'x',{
writable:false,
});
obj.x='hhha'
document.write(obj.x+'<br/>');
</script>