函数化2

 1 var mammal = function(spec) {
 2         var that = {};
 3 
 4         that.get_name = function() {
 5             return spec.name;
 6         };
 7 
 8         that.says = function() {
 9             return spec.saying || '';
10         };
11         return that;
12     };
13 
14 var myMammal = mammal({
15     name: 'Herb'
16 });
17 
18 //构造器函数Cat
19 var cat = function(spec) {
20         spec.saying = spec.saying || 'meow';
21         var that = mammal(spec);
22         that.purr = function(n) {
23             var i, s = '';
24             for (i = 0; i < n; i += 1) {
25                 if (s) {
26                     s += '-';
27                 }
28                 s += 'r';
29             }
30             return s;
31         };
32         that.get_name = function() {
33             return that.says() + ' ' + spec.name + ' ' + that.says();
34         };
35         return that;
36     };
37 
38 var myCat = cat({
39     name: 'Henrietta'
40 });
41 console.log(myCat.get_name());

 

posted @ 2012-07-13 14:44  小猩猩君  阅读(160)  评论(0编辑  收藏  举报