这样可以吗
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <!DOCTYPE html> <html> <head> <meta charset= "UTF-8" > <title>Document</title> </head> <body> <script type= "text/javascript" > Object.defineProperty(Object, 'freezPolyFill' ,{ value: function (obj){ let i; for (i in obj){ if (obj.hasOwnProperty(i)){ if ( typeof obj[i] === 'object' ){ return Object.freezPolyFill(obj[i]); } Object.defineProperty(obj,i,{ writable: false }) } } Object.seal(obj); } }) const xiaoming = { age:14, name: 'xiaoming' , hobby:{ basketball: true , football: true } } Object.freezPolyFill(xiaoming); </script> </body> </html> |
正在回答 回答被采纳积分+1
前面几条回复错了喔 数组和对象都能验证通过的是下面这个。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
Object.defineProperty(Object, 'freezePolyfill', {
value: function(obj) {
var i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (typeof obj[i] === 'object' && !isNaN(obj[i].length)) { //是数组的情况
Object.seal(obj[i]);
Object.defineProperty(obj, i, {
writable: false
});
}else if (typeof obj[i] === 'object'){ //是对象的情况
Object.freezePolyfill(obj[i]);
}else{
Object.defineProperty(obj, i, {
writable: false
});
}
}
}
Object.seal(obj);
}
});
const xiaoming = {
age:14,
name:'xiaoming',
hobby:{
basketball:true,
football:true
},
parents:[1]
}
Object.freezePolyfill(xiaoming);
xiaoming.a="15";
xiaoming.age="age";
xiaoming.hobby["basketball"]="bascket1";
xiaoming.parents=[1,2];
console.log(xiaoming);
</script>
</body>
</html>
上面代码有bugObject.seal(obj);需要放在for循环里面。修改如下即可。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
Object.defineProperty(Object,'freezPolyFill',{
value: function(obj){
var i;
for(i in obj){
// console.log(i);
if(obj.hasOwnProperty(i)){
if(typeof obj[i] === 'object'){
return Object.freezPolyFill(obj[i]);
}
console.log(i);
Object.defineProperty(obj,i,{
writable:false
})
}
Object.seal(obj);
}
}
})
const xiaoming = {
age:14,
name:'xiaoming',
hobby:{
basketball:true,
football:true
}
}
Object.freezPolyFill(xiaoming);
xiaoming.a="15";
xiaoming.hobby["basketball"]="bascket1";
console.log(xiaoming);
</script>
</body>
</html>
- 参与学习 人
- 提交作业 209 份
- 解答问题 3299 个
本路径是通过ES6基础知识、运用Zepto、Swiper、fullPag等移动端常用工具包、以及当下流行框架Vue,结合多个实战案例,还原真实开发场景,最终实现手机端购物商城网页开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧