1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>js封装</title>
6 </head>
7 <body>
8
9 </body>
10 </html>
11 <script type="text/javascript">
12 //javascript中面向对象的5种写法
13 //定义Circle类,拥有成员变量r,常量PI和计算面积的成员函数area()
14
15 //第一种写法:比较正规的写法
16 function Circle(r){
17 this.r = r;
18 }
19 Circle.PI = 3.14159;
20 Circle.prototype.area = function (){
21 return Circle.PI * this.r * this.r;
22 }
23 var c = new Circle(2.0);
24 console.log(c.area());
25
26 //第二种写法:工厂方法
27 var Circle = function (){
28 var obj = new Object();
29 obj.PI = 3.14159;
30
31 obj.area = function (r){
32 return this.PI * r * r;
33 }
34 return obj;
35 }
36 var c = new Circle();
37 console.log(c.area(2.0));
38
39 //第三种写法
40 var Circle = new Object();
41 Circle.PI = 3.14159;
42 Circle.area = function (r){
43 return this.PI * r * r;
44 }
45 console.log(Circle.area(2.0));
46
47 //第四种写法:JSON写法
48 var Circle = {
49 "PI":3.14159,
50 "area":function(r){
51 return this.PI * r * r;
52 }
53 }
54 console.log(Circle.area(2.0));
55
56 //第五种写法
57 var Circle = new function("this.PI = 3.14159;this.area =function(r){return r * r * PI;}");
58 console.log((new Circle()).area(2.0));
59
60 </script>