JavaScript对象
Posted 瑾言**
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript对象相关的知识,希望对你有一定的参考价值。
1.javascript对象
在JS中,对象是一组无序的属性和方法的集合。
2. 创建对象的三种方式
(1)
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 </head> 9 10 <body> 11 <script> 12 //这是创建对象最简的一种方式,用大括号{} 将对象的属性和方法包围起来 13 var person = { 14 name: "zhangsan", 15 age: 15, 16 sex: "boy", 17 show: function(){ 18 console.log("Hello , I am zhangsan ") 19 } 20 } 21 //调用对象的属性,有两种方法 22 //(1) 对象名.属性名 23 //(2) 对象名["属性名"] 24 console.log(person.name); 25 console.log(person["age"]); 26 console.log(person.show()); 27 </script> 28 </body> 29 30 </html>
(2)利用 new object 创建对象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> //利用 new object 创建对象 var zhangsan = new Object(); //只能用等号赋值的方法添加对象的的属性和方法 zhangsan.name = "zhangsan"; zhangsan.age = 123; zhangsan.sex = "男"; zhangsan.show = function(){ console.log("你好,我是张三") } //调用看看 console.log(zhangsan.name); console.log(zhangsan.sex); console.log(zhangsan.show()); </script> </body> </html>
(3)使用构造函数创建对象
原因: 前两种方式一次只能创建一个对象
JS中的构造函数:就是将一些对象的相同的属性和方法,抽象出来,封装到一个函数中,这个函数就是构造函数
构造函数:
//构造函数名的首字母要大写
function 构造函数名(形参1,形参2,..){
this.属性 = 值;
this.方法 = function(){};
}
new 构造函数名();
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 </head> 8 <body> 9 <script> 10 function Student(uname,uage,uschool){ 11 this.name = uname; 12 this.age = uage; 13 this.school = uschool; 14 this.show = function(){ 15 console.log("hello, I am " +uname+ ",and my school is " + uschool); 16 17 } 18 } 19 20 var zhangsan = new Student("zhangsan",22,"shandondaxue"); 21 var lisi = new Student("lisi",77,"beijingdaxue"); 22 console.log(zhangsan.show()); 23 console.log(lisi.show()); 24 25 26 </script> 27 </body> 28 </html>
3.遍历对象的属性 for .... in
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var zhangsan = { name:"zhangsan", age:22, id:20161209733, phone:188888888, address:"beijing" } //遍历对象的属性 for .. in for( var k in zhangsan ){ //k 属性名 console.log(k); //对象名[k] 属性值 console.log(zhangsan[k]); } </script> </body> </html>
以上是关于JavaScript对象的主要内容,如果未能解决你的问题,请参考以下文章