/* 继承 : 从父类(父构造函数)得到相关的属性和方法,给子类(子构造函数)。那么通过子构造函数创建出来的对象,就能够拥有父构造函数的属性和方法。
继承:复用代码的一种形式。 */
//如何实现继承:
//1. 完成属性的继承 父类.call()
//2. 完成方法的继承
function Person(){ //父类
this.username = 'xiaoming';
this.age = 20;
}
Person.prototype.showName = function(){
return '我叫:' + this.username;
};
function Child(){ //子类
Person.call(this); // 通过改变this指向,来继承父类的属性
}
//Child.prototype = Person.prototype; //对象引用的问题
for(var attr in Person.prototype){ //用浅拷贝解决这个互相影响的问题
Child.prototype[attr] = Person.prototype[attr];
}
Child.prototype.showJob = function(){};
var p1 = new Person();
var c1 = new Child();
console.log(p1);
console.log(c1);
//console.log( c1.username );
//console.log( c1.showName() );
继承
最新推荐文章于 2023-07-18 15:45:50 发布