Ray's playground

 

Inheritance(Chapter 5 of JavaScript: The Good Parts)

code
 1 var Mammal = function (name) {
 2                 this.name = name;
 3             };
 4 
 5             Mammal.prototype.get_name = function () {
 6                 return this.name;
 7             }
 8 
 9             Mammal.prototype.says = function () {
10                 return this.saying || '';
11             };
12 
13             var myMammal = new Mammal('Herb the Mammal');
14             var name = myMammal.get_name();
15             alert(name);
16 
17             var Cat = function (name) {
18                 this.name = name;
19                 this.saying = 'meow';
20             };
21 
22             Cat.prototype = new Mammal();
23             Cat.prototype.purr = function (n) {
24                 var i, s = '';
25                 for (i = 0; i < n; i += 1) {
26                     if (s) {
27                         s += '-';
28                     }
29                     s += 'r';
30                 }
31                 return s;
32             };
33 
34             Cat.prototype.get_name = function () {
35                 return this.says() + ' ' + this.name + ' ' + this.says();
36             };
37 
38 var myCat = new Cat('Henrietta');
39 
40 alert(myCat.says());
41 alert(myCat.purr(5));
42 alert(myCat.get_name());

 

posted on 2010-07-10 11:46  Ray Z  阅读(171)  评论(0编辑  收藏  举报

导航