文章目录
  1. 1. 原型链最基本的一种继承–过多继承了没用的属性
  2. 2. 借用构造函数实现继承 – 每次构造函数都要多走一个函数 无法继承借用构造函数的原型
  3. 3. 共享原型—不能随便改动自己的原型
  4. 4. 圣杯模式(较好的继承实现,一般采用此方式)

JavaScript实现继承的几种方式

原型链最基本的一种继承–过多继承了没用的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Grand.prototype.lastName = "Deng";
function Grand() {

}
var grand = new Grand();

Father.prototype = grand;
function Father() {
this.name = "123";
this.fortune={
a:123
}
}
var father = new Father();

Son.prototype = father;
function Son() {
this.hobbit="smoke";

}
var son = new Son();

借用构造函数实现继承 – 每次构造函数都要多走一个函数 无法继承借用构造函数的原型

1
2
3
4
5
6
7
8
9
10
function Person(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
function Student(name,age,sex,grade){
Person.call(this,name,age,sex);
this.grade=grade;
}
var student = new Student("a",12,1,1);

共享原型—不能随便改动自己的原型

1
2
3
4
5
6
7
8
9
10
11
12
Father.prototype.lastName="Deng"
function Father(){

}

function Son(){

}
//未封装
Son.prototype=Father.prototype;
var son = new Son();
var father = new Father();

我们对共享原型模式加以封装改造

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Father() {

}

function Son() {

}
//target 继承 origin
function inherit(Target, Origin) {
Target.prototype = Origin.prototype
}
//必须先继承后用
inherit(Son, Father);
var son = new Son();

圣杯模式(较好的继承实现,一般采用此方式)

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
// function inherit(Target, Origin) {
// function F() {};
// F.prototype = Origin.prototype;
// Target.prototype = new F();
// Target.prototype.constructor = Target;
// Target.prototype.uber = Origin.prototype;
// }
//比较专业的写法
var inherit = (function () {
var F = function () {};
return function (Target, Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
}());
Father.prototype.lastName = "Deng"

function Father() {

}

function Son() {

}
inherit(Son, Father);
var son = new Son();
var father = new Father();
文章目录
  1. 1. 原型链最基本的一种继承–过多继承了没用的属性
  2. 2. 借用构造函数实现继承 – 每次构造函数都要多走一个函数 无法继承借用构造函数的原型
  3. 3. 共享原型—不能随便改动自己的原型
  4. 4. 圣杯模式(较好的继承实现,一般采用此方式)