Appearance
js 继承
原型链继承 new
优点:可以使用父类的原型方法
缺点:1.子类实例不能给父类传参;2:子类共享父类引用类型属性
js
function Parent() {
this.name = 'mt';
this.obj = {
age: 18
};
}
function Child() {
this.name = 'mtc';
}
Child.prototype = new Parent();
var child1 = new Child();
console.log(child1.name); // 'mtc'
console.log(child1.obj); // {age:18}
var child2 = new Child();
console.log(child2.obj); // {age:18}
// 修改child1.obj.age
child1.obj.age = 200;
// 父的引用类型指向被所有子集共享 child2 也会改变
console.log(child2.obj); // {age:200}
// 若只修改child1.obj ={xx:xx}
// child2不会发生改变,因为child1又给obj开辟了一块新的内存空间,指向了新的地址与其他的不会相互影响
// 父原型方法也会继承
Parent.prototype.sex = 1;
console.log(child1.sex); // 1