JavaScript对象
JavaScript 中的所有事物都是对象:字符串、数值、数组、函数...
此外,JavaScript 允许自定义对象。
创建 JavaScript 对象
通过 JavaScript,您能够定义并创建自己的对象。
创建新对象有两种不同的方法:
- 定义并创建对象的实例
- 使用函数来定义对象,然后创建新的对象实例
<!doctype html> <html> <head> <meta charset="utf-8"/> <title></title> </head> <body> <script type="text/javascript"> //通过对象字面量的形式创建对象 var obj={};//没有任何属性的对象 alert(typeof obj); var obj1={x:1,y:2,z:3}; var obj2={ 'x':1, "y":2, username:'king', 'for':'javascript关键字应放在引号之间', 'firstname':'queen', married:true, test:null, test1:undefined, salary:12.3, person:{username:'king',age:12,addr:'北京'} } //通过new object()来创建对象 var obj3=new Object();//创建一个空对象 var arr=new Array();//创建一个空数组 var date=new Date();//日期时间对象 var reg=new RegExp('js');//创建正则对象 //通过构造函数创建对象 function Test(){ } var obj=new Test(); function Test1(num1,num2){ this.n1=num1; this.n2=num2; } var obj5=new Test1(5,6); alert(obj5 instanceof Test); var obj6=Object.create({x:1}); var obj7=Object.create(null); //创建一个普通的空对象 var obj8=Object.create(Object.prototype); </script> </body> </html>
<!doctype html> <html> <head> <meta charset="utf-8"/> <title></title> </head> <body> <script type="text/javascript"> //对象字面量 var person={ username:'king', age:12, salary:1234.56, addr:'北京', sex:'男' }; person.username; console.log('用户名为:'+person.username+"\n"+'性别为'+person.sex); console.log('薪水:'+person['salary']+'\n'+'地址:'+person['addr']); //如果属性不确定时需要使用[] var key='username'; console.log(person.key); console.log(person[key]); console.log(person['key']); function PersonInfo(name,age,sex){ this.name=name; this.age=age; this.sex=sex; } var person1=new PersonInfo('king',34,'男'); console.log(person1.name+person['sex']); //添加属性 var obj={};//空对象 obj.username='king'; obj.age=12; obj.arr='上海'; obj['test']='this is a test'; console.log(obj.username+'\n'+obj.age+'\n'+obj.addr+'\n'+obj['test']); //修改指定属性 obj.username='queen'; obj['test']='一堆废话'; console.log('修改之后的名字'+obj.username); console.log(obj.test); //通过delete删除指定属性 delete obj.test; console.log(obj['test']); delete obj.username; console.log(obj['username']); //通过for/in遍历属性 var obj1={ x:1, y:2, test:"this is a test", edu:'麦子学院' }; for(var p in obj1){ console.log(p+'\n'); } //在对象中使用方法遍历 var obj2={ username:'king', age:12, addr:'北京', sayHI:function(){ return 'say hi'; }, info:function(){ return '用户名'+this.username+'\n'+'年龄'+this.age+'地址'+this.addr; } }; console.log(obj2.sayHI()); console.log(obj2.info()); </script> </body> </html>
//通过构造函数来创建对象 function Person(username,age,sex,addr){ this.username=username; this.age=age; this.sex=sex; this.addr=addr; this.info=function(){ return this.username+this.addr; } } var p1=new Person('Queen',34,'女','上海'); console.log(p1.info()); p1.test='this is a tset'; console.log(p1.test); p1.info1=function(){ return 'this is111111111'; }; console.log(p1.info1());