1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Parent()  {
this.name = 'parent'
}

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

function Child() {
this.name = "child";
}

Child.prototype = new Parent();

var child1 = new Child();

console.log(child1.getName());// "child"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function Parent() {
this.arr = [1,2,3];
}

//定义子类
function Child() {}

// 子类继承父类,这里是关键,实现原型链继承
Child.prototype = new Parent();

// 实例化子类
var child1 = new Child();
var child2 = new child();

child1.arr.push(4);

console.log(child1.arr)
console.log(child2.arr)

原型链继承的一个主要问题是包含引用类型值的原型属性会被所有实例共享。换而言之,如果一个实例改变了该属性,那么其他实例的该属性也会被改变