1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 父类
function Parent() {
this.sayHello = function () {
console.log("Hello");
}
}

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

Child.prototype = new Parent()

// 创建两个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. 调用了 2 次 Parent()。
  4. 它在 child 的 prototype 上添加了父类的属性和方法。