1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
5 <title></title>
6 <meta charset="utf-8" />
7 </head>
8 <body>
9 <script type="text/javascript">
10 //javascript有一个内置对象object;利用他可以创建一个空白的对象
11 person = new Object(); //使用object创建对象
12 person.name = "张三"; //添加属性
13 function func() { //定义一个方法,然后把它附加到person
14 alert(this.name);//this关键字指向函数的父对象
15 }
16 Person.showName = func; //这里只有方法名; 如果带();是将方法的返回值赋值给person.showName;
17 Person.showName(); //调用showName()方法
18 </script>
19
20 <script type="text/javascript">
21 //匿名函数
22 function func() {
23 alert(this.name);
24 }
25 person.showName = func;//可以改写为
26 person.showName = function () {
27 alert(this.name);
28 }
29 </script>
30
31 <script type="text/javascript">
32 //无参数的构造函数
33 function Person() {
34 this.name = "zhangsan";
35 this.age = 18;
36 this.show = function () {
37 alert("无参数构造"+this.name+""+this.age);
38 }
39 }
40 //有参数的构造函数
41 function Person(name,age) {
42 this.name=name;
43 this.age=age;
44 this.show = function () {
45 alert("带参数构造"+this.name +" "+ this.age);
46 }
47 }
48 //对象的实例化
49 var p1 = new Person(); //两个构造函数默认执行离代码最近的
50 var p2 = new Person("zhangsan", 18); //创建两次对象;执行两次带参
51 p1.show();//调用对象的方法
52 p2.show();
53 </script>
54
55 <script type="text/javascript">
56 //扩展对象
57 function abc(name,age) {
58 this.name = name;
59 this.age = age;
60 this.show1 = function () {
61 alert(this.name+" "+this.age);
62 }
63 }
64 var a = new abc("zhangsa",18);
65 a.show1();
66 abc.prototype.sex = "男";//添加属性
67 abc.prototype.show2 = function () { //添加方法
68 alert(this.name +" "+ this.sex+" "+this.age);
69 }
70 a.show2();//调用新方法
71 </script>
72
73 <script type="text/javascript">
74 //继承
75 function A() { //父对象
76 this.name = "zhangsan";
77 this.show1 = function () {
78 alert("姓名"+this.name);
79 }
80 }
81 function B() {//子对象
82 this.age = 18;
83 this.show2 = function () {
84 alert("年龄"+this.age);
85 }
86 }
87 B.prototype = new A();
88 var test = new B();
89 this.name = "lisi"; //继承父对象的name属性;并修改值
90 test.show1();//继承"父对象"的show1()方法
91 test.show2();//调用"子对象"的show2()方法
92 </script>
93
94 <script type="text/javascript">
95 //封装
96 function Box(width,length,height) {
97 function volume(a, b, c) {
98 return a * b * c;
99 }
100 this.boxVolume = volume(width,length,height); //把方法的返回值赋值给属性
101 }
102 var box = new Box(1,2,3); //传参
103 alert(box.boxVolume); //弹出属性值
104
105 alert(volume(1,2,3));//不可用
106 </script>
107 </body>
108 </html>