原型继承用法

function Student(props) {
  this.name = props.name || "大佬";
}

Student.prototype.say = function() {
  return "Hello" + this.name;
};

function PrimaryStudent(props) {
  Student.call(this, props);
  this.age = props.age || 18;
}

`// 不封装用法
// 1.创建F()空函数
var F = function() {};

// 2.F原型指向Student.prototype
F.prototype = Student.prototype;

// 3.PrimaryStudent原型指向一个新的new F()对象
PrimaryStudent.prototype = new F();

// 4.PrimaryStudent.prototype.constructor 修复成 PrimaryStudent
PrimaryStudent.prototype.constructor = PrimaryStudent;`;

// 封装上一段的函数 形成通用的 inherits
function inherits(Child, Parent) {
  var F = function() {};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
}

inherits(PrimaryStudent, Student);

// 在PrimaryStudent上定义原型方法
PrimaryStudent.prototype.getAge = function() {
  return this.age;
};

// 创建小明
var xiaoming = new PrimaryStudent({
  name: "小明",
  age: 26
});

xiaoming.name; // 小明
xiaoming.age; // 26

xiaoming.__proto__ === PrimaryStudent.prototype; // true
xiaoming.__proto__.__proto__ === Student.prototype; // true

xiaoming instanceof PrimaryStudent; // true
xiaoming instanceof Student; // true

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
48
49
50
51
52
53
54
55
56

PS:   来源:廖雪峰 JavaScript 教程 原型继承

上次更新: 2019-10-25 16:39