继承:
有两类:
父类:也叫基类
子类:也叫派生类
好处:可以让子类去继承父类的属性和方法 子类中本来没有,如果继承了父类的,子类就可以使用这
些属性和方法了
一、原型继承
特点:
1)继承父类的公有属性和私有属性 作为子类的公有属性
2)核心代码:Son.prototype = new Father();
<script>
// Father叫父类 基类 let f1 = new Father()
function Father(a){
this.a = a; // 叫父类的私有属性
}
// 对于f1来说,getA是它的公有属性
Father.prototype.getA = function(){
console.log(this.a);
}
// 此时Father和Son没有任何关系
// 子类 派生类 Son中有没有a 可以让Son继子Father中的a
function Son(){
}
let son = new Son();
console.log(son.a);
son.getA(); //
</script>
<script>
function Father(a){
this.a = a;
}
Father.prototype.getA = function(){
console.log(this.a);
}
function Son(){
}
// 改变了Son的原型对象 说白了,改变了Son原型
// 让Son继承了Father的公有属性和私有属性,作为Son的公有属性
Son.prototype = new Father();
// 修正原型对象上的contructor指向
Son.prototype.constructor = Son;
let son = new Son();
console.log(son.a);
son.getA();
</script>
二、call继承
特点:
1)继承父类的私有属性 作为子类的私有属性 用的不多 一般情况下,别人私有的,是不想
让别人继承
2)Father.call(this);
<script>
function Father(){
// 改变的仅仅是此this指向
this.a = 110;
}
Father.prototype.getA = function(){
console.log(this.a);
}
// let f1 = new Father()
function Son(){
// Father是类 是函数 是对象 是方法
// .call 作用:1)改变this指向 2)让Father执行
// 指向谁call的第1个参数 指向this
Father.call(this)
}
let son = new Son();
console.log(son.a);
son.getA()
</script>
三、组合继承
特点:
1)会继承父的私有属性和公有属性,作为子类的公有属性
2)继承父类的私有属性,作为子的私有属性
3)父的私有属性被继承了两次,当我们访问一个属性时,会先访问私有属性
<script>
// 特点:
// 1)会继承父的私有属性和公有属性,作为子类的公有属性
// 2)继承父类的私有属性,作为子的私有属性
// 3)父的私有属性被继承了两次,当我们访问一个属性时,会先访问私有属性
function Father() {
this.a = 110;
}
Father.prototype.getA = function () {
console.log(this.a);
}
function Son() {
// call继承
Father.call(this)
}
// 原型继承
Son.prototype = new Father();
Son.prototype.constructor = Son;
let son = new Son();
console.log(son.a); // 访问a 访问的是son的私有属性
son.getA()
</script>
四、只想继承父类的公有属性,作为子类的公有属性
核心代码:
var Fn = function(){};
Fn.prototype = Father.prototype;
Son.prototype = new Fn();
<script>
function Father() {
this.a = 110;
}
Father.prototype.getA = function () {
console.log("我是Father的公有属性");
console.log(this.a);
}
// 把Father的原型对象,赋值给Son的原型对象 这样就继承了原型对象中的getA
// 不好,因为Son和Father共享一个原型对象,当通过Son修改了原型对象,也会影响Father的原型对象
// Son.prototype = Father.prototype;
var Fn = function (){}
// 此时Fn和Father共享同一个原型对象 如果你不对Fn的原型对象操作,就会影响到Father的原形对象
Fn.prototype = Father.prototype;
// new Fn(); 创建出来一个新的对象
Son.prototype = new Fn();
function Son() {
}
let son = new Son();
console.log(son.a); // 访问a 访问的是son的私有属性
son.getA()
</script>