<!doctype html>
<html>
<head>
<title>标题</title>
<meta charset="utf-8">
<script>
"use strict";
var emp={
id:1001,
name:"eric",
salary:10000
};
//id属性设置为只读
//salary属性设置为禁止遍历
//添加age属性,值为25,可读写,可遍历,可配置
Object.defineProperties(emp,{
id:{
writable:false,
configurable:false
},
salary:{
enumerable:false,
configurable:false,
},
age:{
value:25,
writable:true,
enumerable:true,
configurable:true
}
});
//emp.id=1002;//报错!
//delete emp.id;//报错!
for(var key in emp){
console.log(key+":"+emp[key]);
}
emp.age++;
console.log(emp.age);//26
/*设置id属性为只读
Object.defineProperty(emp,"id",{
writable:false,
configurable:false//不可逆
});*/
//delete emp.id;//禁止删除
/*
var id_attrs=
Object.getOwnPropertyDescriptor(
emp,"id"
);
console.dir(id_attrs)
*/
/*
Object.defineProperty(emp,"id",{
writable:true
});//报错: 不允许重定义id属性
*/
//emp.id=1002;//报错:不允许给只读属性赋值
//console.log(emp.id);
//设置salary属性不可遍历:
/*
Object.defineProperty(
emp,"salary",{
enumerable:false,
configurable:false,
}
);
for(var key in emp){
console.log(key+":"+emp[key]);
}
console.log(emp.salary);
*/
/*
Object.defineProperty(emp,"age",{
value:25,
writable:true,
enumerable:true,
configurable:true,
});
console.dir(
Object.getOwnPropertyDescriptor(
emp,"age"
)
);
emp.age++;
console.log(emp.age);
*/
</script>
</head>
<body>
</body>
</html>
javascript面向对象(七)
最新推荐文章于 2024-01-07 18:00:00 发布