person.sayName=function(){console.log("my name is "+this.name);};if("sayName"inperson){console.log("sayName is in person");// sayName is in person}if("toString"inperson){console.log("toString is in person");// toString is in person}if(person.hasOwnProperty("isCitizen")){console.log("has own property isCitizen");// has own property isCitizen}if(person.hasOwnProperty("toString")){// falseconsole.log("has own property toString");}
varqiushi={// Javascript中的一种convention,以下划线开始的property被当做private的,但其实还是public的_age:27,getage(){console.log("read age");returnthis._age;},setage(value){console.log("set age");this._age=value;}};console.log(qiushi.age);// read age 27qiushi.age=28;// set age
property的属性
遍历property(enumerable)
可以使用for-in循环来遍历每个property:
12345678910
varusa={state:55,population:320000000};for(varpropinusa){// keyconsole.log("property : "+prop);// valueconsole.log("property value : "+usa[prop]);}
// state is enumerable : trueconsole.log("state is enumerable : "+usa.propertyIsEnumerable("state"));varkeys=Object.keys(usa);console.log("length"inkeys);// true// length is enumerable : falseconsole.log("length is enumerable : "+usa.propertyIsEnumerable("length"));
varperson1={_name:"Nicholas"};Object.defineProperty(person1,"name",{get:function(){console.log("Reading name");returnthis._name;},set:function(value){console.log("Setting name to %s",value);this._name=value;},enumerable:true,configurable:true});