属性的遍历,删除,检测

来源:互联网 发布:乒乓球输给日本 知乎 编辑:程序博客网 时间:2024/05/29 03:10
先定义三种不同类型的属性(方法也可当作属性来看待)
//声明类和类的构造函数function Person(name,age){ this.name=name; //类的属性this.age=age;this.sayHello=function(){ //类的方法document.writeln("Hello I'm " + this.name);}this.setName=function(name){this.name=name;}this.setAge=function(age){this.age=age;}}var person = new Person('xiao', 21);//类的静态属性方法Person.Max_Age=120; //类的静态属性Person.cry=function(){ //类的静态方法document.writeln('www...'); //所有Person的哭声是一样的}//类的prototype属性方法function Chinese(){ this.sayHello=function(){ //覆盖Person的sayHello()方法document.writeln('你好! 我是' + this.name);}}Chinese.prototype=new Person('xiaomin');var xiaomin = new Chinese();



1. 遍历属性
for(var p in xiaomin){document.writeln(p+'='+xiaomin[p]);}//Object.keys()返回所有属性名document.writeln(Object.keys(person));  //=>name,age,sayHello,setName    //Object.getOwnPropertyNames()返回所有自有属性名document.writeln(Object.getOwnPropertyNames(xiaomin));  //=>sayHello 



2. 删除属性
document.writeln(person.age); //=> 21document.writeln(delete person.age);  //=> truedocument.writeln(person.age);  //=> undefineddocument.writeln(delete person.weight);  //=> truedocument.writeln(delete person.sayHello);  //=> trueif(person.sayHello){person.sayHello();  // 不执行}else{  document.writeln('there is no sayHello in person.');  //执行,说明方法已被删除}document.writeln(delete Person.Max_Age);  //=> truedocument.writeln(Person.Max_Age); //=>undefined 静态属性可被删除document.writeln(delete Person.cry);  //=> true//Person.cry(); //抛出异常, 静态方法可被删除  document.writeln('=============');  //=> truedocument.writeln(Chinese.prototype.name);  //=> xiao document.writeln(delete Chinese.prototype.name);  //=> true document.writeln(Chinese.prototype.name);  //=> undefined, prototype中的属性被删除document.writeln(delete Chinese.prototype);  //=> false, prototype不能被删除document.writeln(delete xiaomin.sayHello); //=> true//xiaomin.sayHello(); //抛出异常, 继承的方法可被删除  



3. 检测属性
//JS对象可看作属性的集合,我们经常会检测集合中成员的所属关系--判断某个属性是否存在于某个对象中。xiaomin.weight=100;//用in判断属性/方法是否在对象中document.writeln('weight' in xiaomin);   //=> true, xiaomin的自有属性/方法可被in检测document.writeln('setAge' in xiaomin);   //=> true, xiaomin的继承属性/方法可被in检测 //用hasOwnProperty判断属性/方法是否是对象自有的(非继承的)document.writeln(xiaomin.hasOwnProperty('weight')); //=> true, weight是xiaomin的自有属性/方法document.writeln(xiaomin.hasOwnProperty('setAge')); //=> false,  setAge不是xiaomin的自有属性/方法//propertyIsEnumerable是hasOwnProperty的增强版,只有检测到是自有属性且这个属性的可枚举(可遍历)性为true时才返回truedocument.writeln(xiaomin.propertyIsEnumerable('weight')); //=> truedocument.writeln(xiaomin.propertyIsEnumerable('setAge')); //=> false 非自有属性document.writeln(xiaomin.propertyIsEnumerable('toString')); //=> false 非可枚举属性//用"!=="判断一个属性是否undefineddocument.writeln(xiaomin.weight !== undefined); //=> truedocument.writeln(xiaomin.setAge !== undefined); //=> true//注意,上例中使用的是"!=="而不是"!=", "!=="可区分undefined和null.
原创粉丝点击