面向对象的JavaScript-003

1.

 1 // Since JavaScript doesn't exactly have sub-class objects, prototype is a useful workaround to make a “base class” object of certain functions that act as objects. For example:
 2     var Person = function() {
 3       this.canTalk = true;
 4     };
 5 
 6     Person.prototype.greet = function() {
 7       if (this.canTalk) {
 8         console.log('Hi, I am ' + this.name);
 9       }
10     };
11 
12     var Employee = function(name, title) {
13       Person.call(this);
14       this.name = name;
15       this.title = title;
16     };
17 
18     Employee.prototype = Object.create(Person.prototype);
19     Employee.prototype.constructor = Employee;
20 
21     Employee.prototype.greet = function() {
22       if (this.canTalk) {
23         console.log('Hi, I am ' + this.name + ', the ' + this.title);
24       }
25     };
26 
27     var Customer = function(name) {
28       Person.call(this);
29       this.name = name;
30     };
31 
32     Customer.prototype = Object.create(Person.prototype);
33     Customer.prototype.constructor = Customer;
34 
35     var Mime = function(name) {
36       Person.call(this);
37       this.name = name;
38       this.canTalk = false;
39     };
40 
41     Mime.prototype = Object.create(Person.prototype);
42     Mime.prototype.constructor = Mime;
43 
44     var bob = new Employee('Bob', 'Builder');
45     var joe = new Customer('Joe');
46     var rg = new Employee('Red Green', 'Handyman');
47     var mike = new Customer('Mike');
48     var mime = new Mime('Mime');
49 
50     bob.greet();
51     // Hi, I am Bob, the Builder
52 
53     joe.greet();
54     // Hi, I am Joe
55 
56     rg.greet();
57     // Hi, I am Red Green, the Handyman
58 
59     mike.greet();
60     // Hi, I am Mike
61 
62     mime.greet();

posted @ 2016-05-24 14:31  shamgod  阅读(199)  评论(0编辑  收藏  举报
haha