js继承

原型链继承

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
function Parent() {
this.name = 'jchermy';
}

Parent.prototype.getName = function() {
console.log(this.name);
}

function Child() {

}

Child.prototype = new Parent();

var child1 = new Child();
console.log(child1.getName()); //jchermy
```
### 缺点
> 引用类型的属性被所有实例共享
> 在创建Child实例时,不能向Parent传参

# 构造函数继承(call bind apply

``` js
function Parent() {
this.names = ["aa", "bb"];
}

function Child() {
Parent.call(this);
}

var child1 = new Child();)

缺点

缺点:方法都在构造函数中定义,每次创建实例都会创建一遍方法

组合继承

function Parent(name) {
    this.name = name;
    this.colors = ["red", "blue"];
}

Parent.prototype.getName = function() {
    console.log(this.name);
}

function Child(name, age) {
    Parent.call(this, name); 
    this.age = age;
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

var child1 = new Child("aa", 18);
child1.colors.push("black");

child1.name; //"aa"
child1.age; //18
child1.colors; //["red", "blue","black"]

var child2 = new Child("bb", 20);
child2.name; //"bb"
child2.age; //20
child2.colors; //["red", "blue"]

ES6 class 继承

ES6的继承:通过extends实现继承

class A {}

class B extends A {
  constructor() {
    super();
    console.log(super.valueOf() instanceof B); // true,valueOf()返回该对象的原始值。
  }
}

let b = new B();
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×