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
// 父类
function Parent() {
this.sayHello = function () {
console.log("Hello");
}
}

Parent.prototype.a = "我是父类prototype上的属性";
// 子类
function Child() {
Parent.call(this)
}

// 创建一个没有实例方法的父类实例作为子类的原型
Child.prototype = Object.create(Parent.prototype);
// 修复构造函数的指向
Child.prototype.constructor = Child;

// 创建两个Child实例
var child1 = new Child();
var child2 = new Child();

console.log(child1.sayHello === child2.sayHello);// false

var parentObj = new Parent();
console.log(parentObj.a);//我是父类prototype上的属性
console.log(child1.a)//我是父类prototype上的属性
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
// 父类
function Parent() {
this.sayHello = function () {
console.log("Hello");
}
}

Parent.prototype.a = "我是父类prototype上的属性";
// 子类
function Child() {
Parent.call(this)
}

Child.prototype.childFunction = ()=> {
console.log("我是child方法");
}

// 创建一个没有实例方法的父类实例作为子类的原型
Child.prototype = Object.create(Parent.prototype);
// 修复构造函数的指向
Child.prototype.constructor = Child;

// 创建两个Child实例
var child1 = new Child();
child1.childFunction();
// TypeError: child1.childFunction is not a function
// at <anonymous>:25:8
// at mn (<anonymous>:16:5455)

优点:
1 ,原型属性不会被共享
2 ,可以继承父类的原型链上的属性和方法
3 .只调用了 1 次 Parent(), 因此,它不会在 Child 的prototype 上添加 Parent 的属性和方法。
缺点:
Child.prototype的原始属性和方法会丢失。