Javascript 面向对象之继承的实现

Javascript 里面实现继承的代码

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

//定义Persion 类
function Persion(name, age) {
this.name = name;
this.age = age;
}

Persion.prototype.hi = function(){
console.log("Hi my name is " + this.name + ", I'm " + this.age + ' years old now.');
}

Persion.prototype.LEGS_NUM = 2;
Persion.prototype.ARMS_NUM = 2;
Persion.prototype.walk = function(){
console.log(this.name + " is walking...");
}

//定义Student 类
function Student(name, age, className){
Persion.call(this, name, age);
this.className = className;
}

//将Student类的原型指向Persion的原型
Student.prototype = Object.create(Persion.prototype);
Student.prototype.constructor = Student;

//复写Persion中的hi 方法
Student.prototype.hi = function(){
console.log("Hi my name is " + this.name + ", I'm " + this.age + " years old now, and from " + this.className + "." );
}

//定义Student中的learn 方法
Student.prototype.learn = function(subject){
console.log(this.name + " is learning " + subject + " at " + this.className);
}




//实例化Student类
var jack = new Student("Jack", 27, 'Class 3, Greade 2');

jack.hi(); //Hi, my name is Jack, I'm 27 years old now, and from Class 3, Greade 2.
jack.LEGS_NUM; // 2
jack.ARMS_NUM; // 2
jack.learn('math') // Jack is learning math at Class 3, Greade 2.