javascript如何封装函数?

通常写js组件开发的,都会用到匿名函数的写法去封装一个对象,与外界形成一个闭包的作用域。封装,全天下漫天遍野的封装,JQuery,EXT和Prototype.js封装的是javascript,jQuery uI和jQuery mobile封装着jQuery,java中的JDBC在spirng,Hibernate等框架封装着。

 1 <!doctype html>
 2 <html >
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 6     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7     <title>Document</title>
 8 </head>
 9 <body>
10 <script type="text/javascript">
11     var beibei = {
12         init:function () {
13             console.log('come in here!');
14         }
15     };
16     beibei.init();
17 
18     //构造函数
19     function Person() {
20         this.name = "beibei";
21         this.age = 26;
22         this.getName = function () {
23             return this.name;
24         }
25     }
26     var person = new Person();
27     console.log(person.age);
28     console.log(person.getName());
29 
30     function Person(name,age) {
31         this.name = name;
32         this.age = age;
33         this.getName = function () {
34             return this.name;
35         }
36     }
37 
38     var p1 = new Person("beibei",10);
39     console.log(p1.name);
40     console.log(p1.age);
41     console.log(p1.getName());
42 
43     //这样写是没问题的 但是 有一点缺陷 就是 每个对象都维护相同的方法实例 而其实它们可以共享此方法 而不必每个对象都生成此实例
44     //在java语言中 面向对象的思想中 有一条“继承”既然此方法对于每个对象来说是公用的 那么可以在它的父类中实现
45     //在javascript中继承 是基于原型对象的继承 在原型对象中实现此方法,那么每个对象调用次方法时 首先查看自己是否有此方法 如果有 调用自己的方法
46     //如果没有 去原型对象中查询 调用原型对象的方法 是不是和java中的继承差不多呢? 这是修改后的代码。
47 
48     function Person(name,age) {
49         this.name = name;
50         this.age = age;
51     }
52 
53     Person.prototype.getName = function () {
54         return this.name;
55     }
56 
57     var p1 = new Person("beibei",10);
58     console.log(p1.name);
59     console.log(p1.age);
60     console.log(p1.getName());
61 
62     //对象字面量的形式构造对象
63     var p1 = {
64         name:"beibei",
65         age:10,
66         getName:function () {
67             return this.name;
68         }
69     }
70     console.log(p1.name);
71     console.log(p1.age);
72     console.log(p1.getName());
73     
74 </script>
75 </body>
76 </html>