JavaScript对象
2021-02-07 21:17
标签:nbsp zhang 对象 width span 函数名 方法 原因 调用 1.JavaScript对象 在JS中,对象是一组无序的属性和方法的集合。 2. 创建对象的三种方式 (1)
(2)利用 new object 创建对象 (3)使用构造函数创建对象 原因: 前两种方式一次只能创建一个对象 JS中的构造函数:就是将一些对象的相同的属性和方法,抽象出来,封装到一个函数中,这个函数就是构造函数 构造函数: //构造函数名的首字母要大写 function 构造函数名(形参1,形参2,..){ this.属性 = 值; this.方法 = function(){}; } new 构造函数名(); 3.遍历对象的属性 for .... in JavaScript对象 标签:nbsp zhang 对象 width span 函数名 方法 原因 调用 原文地址:https://www.cnblogs.com/zysfx/p/12774156.html 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>Documenttitle>
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>
DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
meta name="viewport" content="width=device-width, initial-scale=1.0">
title>Documenttitle>
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>
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>Documenttitle>
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>
DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
meta name="viewport" content="width=device-width, initial-scale=1.0">
title>Documenttitle>
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>
上一篇:冒泡排序
下一篇:Spring---Aop