示例如下:
<script type="text/javascript">
var obj={}
Object.defineProperty(obj,'x',{
value:100
});
document.write(obj.x)
</script>
默认情况如下:
<script type="text/javascript">
var obj={}
Object.defineProperty(obj,'x',{
value:100
});
document.write(obj.x+'
')
obj.x=123;
document.write(obj.x)
</script>
此时writable值默认为false,所以x没有被更改,
若在上述代码中加入writable:true
则效果如图:
代码及效果如下:
<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后得:
若为默认值,则:
<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+'
');
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+'
');
</script>