面向对象的核心概念就是Class,在javaScript里面实际是没有Class的,但是可以模拟出Class的概念。JavaScript的每个对象Object在创建的时候都会先从prototype复制一个对象的初始版本,然后才加入自己的一些字段和方法,实际上function也是一个对象,所以我们要定义新的对象,就使用function。代码如下:

 1Object.prototype.isUndefined = function(objProperty)
 2{
 3    return typeof objProperty == "undefined";
 4}
;
 5String.NewLine = "\n";
 6
 7
 8/// <sumary>
 9///   Class kPerson
10/// </sumary>
11function kPerson(strName, numAge, boolGood)
12{
13    this.__strName__ = strName;
14    this.__numAge__ = numAge;
15    this.__boolGood__ = boolGood;
16    
17}
;
18kPerson.prototype.changeName = function(strNewName)
19{
20    this.__strName__ = strNewName;
21}
;
22kPerson.prototype.grow = function()
23{
24    if (isUndefined(this.__numAge__))
25    {
26        this.__numAge__ = 0;
27    }

28    else
29    {
30        this.__numAge__ += 1;
31    }

32}
;
33kPerson.prototype.toString = function()
34{
35      return "Name: " + this.__strName__ + String.NewLine + 
36       "Age:  " + this.__numAge__ + String.NewLine + 
37       "Good: " + this.__boolGood__ + String.NewLine;
38}
;
39
40/// <sumary>
41///   Class kStudent
42/// </sumary>
43function kStudent(strName, numAge, numScore)
44{
45    kPerson.call(this, strName, numAge, true);
46    this.__numScore__ = numScore;
47}
;
48kStudent.prototype = new kPerson();
49kStudent.prototype.setScore = function(numScore)
50{
51    this.__numScore__ = numScore;
52}
;
53kStudent.prototype.toString = function()
54{
55    return "Name: " + this.__strName__ + String.NewLine + 
56       "Age:  " + this.__numAge__ + String.NewLine + 
57       "Good: " + this.__boolGood__ + String.NewLine +
58       "Score:" + this.__numScore__ + String.NewLine;
59}

60
61
62function Test()
63{
64    
65    var objPerson = new kPerson("Joe"2);
66    objPerson.grow();
67    objPerson.grow();
68    objPerson.changeName("Eric");
69    alert(objPerson.toString());
70    // result :
71    // Name: Eric
72    // Age: 4
73    // Good: undefined
74    
75    var objStudent = new kStudent("Joe", undefined, 80);
76    objStudent.grow();
77    objStudent.grow();
78    objStudent.changeName("Alen");
79    objStudent.setScore(100);
80    alert(objStudent.toString());
81    // result :
82    // Name: Alen
83    // Age: 1
84    // Good: true
85    // Score: 100
86}




posted on 2008-01-17 14:01  Liu Jian  阅读(279)  评论(0编辑  收藏  举报