鄙视: 如何实现类似Java的私有属性和公有属性
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
"use strict";
function Emp(id,ename,age,salary){
this.id=id;
this.ename=ename;
this.salary=salary;
//鄙视: 如何实现类似Java的私有属
性和公有属性
//私有属性: 仅对象内可用的属性
//公有属性: 可用.随意访问的属性
var _age=0;//闭包中的_age等效于Java中的
私有属性
Object.defineProperties(this,{
id:{writable:false},
salary:{enumerable:false},
age:{
get(){return _age},
set(val){
if(val>=18&&val<=65)
_age=val;
else
throw new RangeError("年
龄必须介于18~65之间");
},
enumerable:true,
//configurable:false
}
});
this.age=age;//将age交给已经添加
的访问器属性age
//防篡改:
//Object.preventExtensions(this);
Object.seal(this);
}
var eric=new Emp(1001,"Eric",26,12000);
Object.defineProperty(eric,"id",{
writable:true,configurable:true
})
//eric.id=1002;
//delete eric.ename;
//eric._age=-2;
for(var key in eric){
console.log(key+":"+eric[key]);
}
</script>
</body>
</html>
判断一个对象,是不是数组
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var n=5,s="Hello",b=true,
nu=null, un=undefined,
f=function(){},
obj1=[1,2,3], obj2={},
obj3=new Date(),
obj4={};
obj4.__proto__=obj1;
console.log(
typeof n,//number
typeof s,//string
typeof b,//boolean
typeof nu,//Object
typeof un,//undefined
typeof f,//function
typeof obj1,//Array
typeof obj2,//Object
typeof obj3 //Date
);
//方法一: 判断爹
console.log(
Array.prototype.isPrototypeOf(obj1),
//true
Array.prototype.isPrototypeOf(obj2),
//false
Array.prototype.isPrototypeOf(obj3),
//false
Array.prototype.isPrototypeOf(obj4),
//true
);
//方法一: 判断妈
//2种方式:
//console.log(
//obj1.constructor===Array,
//obj2.constructor===Array,
//obj3.constructor===Array,
//obj4.constructor===Array
//);
console.log(
obj1 instanceof Array,
//obj1.constructor===Array,
obj2 instanceof Array,
obj3 instanceof Array,
obj4 instanceof Array
);
//3. 判断DNA:"[object Array]"
console.log(
Object.prototype.toString.call(obj1)
=="[object Array]", //true
Object.prototype.toString.call(obj2)
=="[object Array]", //false
Object.prototype.toString.call(obj3)
=="[object Array]", //false
Object.prototype.toString.call(obj4)
=="[object Array]" //false
);
//4. isArray()
console.log(
Array.isArray(obj1),
Array.isArray(obj2),
Array.isArray(obj3),
Array.isArray(obj4)
);
</script>
</body>
</html>
(本文所有权归作者所有,如需转载请联系本平台。)