差异化继承

 1 if (typeof Object.beget !== 'function') {
 2     Object.beget = function(o) {
 3         var F = function() {};
 4         F.prototype = o;
 5         return new F();
 6     };
 7 }
 8 
 9 var myMammal = {
10     name: 'Herb the Mammal',
11     get_name: function() {
12         return this.name;
13     },
14     says: function() {
15         return this.saying || '';
16     }
17 };
18 
19 var myCat = Object.beget(myMammal);
20 myCat.name = 'Henrietta';
21 myCat.saying = 'meow';
22 myCat.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 myCat.get_name = function() {
33     return this.says + ' ' + this.name + ' ' + this.says;
34 };
posted @ 2012-07-12 22:15  小猩猩君  阅读(265)  评论(0编辑  收藏  举报