方案一:原型链继承
//父类
function A(x) {
this.x = x
}
A.prototype.getX = function () {
console.log(this.x);
}
//子类
function B(y) {
this.y = y
}
B.prototype = new A(100);//{x:100} ==> __proto__.getX =fn
B.prototype.constructor = B;
B.prototype.getY = function () {
console.log(this.y);
}
let b = new B(200);
b.x //==> undefined
b.getX(); //==> b.getX is not a function
console.log(a);//{x:100} ==> __proto__.getX =fn
console.log(b);//{y:200} ==> __proto__.getY =fn
-
特点:
-
1.js继承是把父类的原型放到子类的原型链上,实例想要调用这些方法,其实是基于__proto__原型链的机制查找完成的
-
2.子类可以重写父类上的属性和方法
-
3.父类中私有的或者公有的属性和方法, 最后都会变成子类公有的属性和方法。
子类构造函数.prototype = 父类的实例;
子类构造函数.prototype.constructor = 子类构造函数
方案二:寄生组合继承
-
function inheritProperty(subType, superType) { function F(){} F.prototype = superType.prototype; superType.prototype.constructor = subType; subType.prototype = new F(); } function SuperType(name) { this.name = name; this.colors = ['red', 'blue', 'greee']; } SuperType.prototype.sayName = function () { console.log(`SuperType.prototype.sayName, this.name=${this.name}`); } function SubType(name, age) { SuperType.call(this, name); this.age = age; } inheritProperty(SubType, SuperType); SubType.prototype.sayAge = function () { console.log(`SubType.prototype.sayAge, this.age=${this.age}`); } const subtype2 = new SubType('fengliang', 18); subtype2.colors.push('yellow'); subtype2.sayAge(); subtype2.sayName(); // console.log(subtype2.colors); const subtype1 = new SubType('someone', 18); subtype1.sayName();
寄生组合继承的原理是:将子类的prototype属性指向父类prototype属性, 然后子类就继承了父类原型上的属性(方法也是属性)。通过父类构造函数的call方法继承父类的属性,这些属性会被实例独享
-
特点:
-
1.最完美的js继承解决方案
-
2.父类私有的属性和方法,成为子类实例私有的属性和方
-
3.父类共有的属性和方法,成为子类的实例公有的属性和方法
方案三:组合继承
-
/*
* 继承 子类继承父类的属性和方法
* 目的 可以让子类的 实例 能够使用父类的属性和方法
* 父类 A
* 子类 B
* */
//父类
function A(x) {
this.x = x;
this.seyHello = function () {
console.log("hello world");
}
}
A.prototype.getX = function () {
console.log(this.x);
}
//子类
function B(y, x) {
this.y = y;
A.call(this, x);
}
B.prototype = new A();
B.prototype.constructor = B;
B.prototype.getY = function () {
console.log(this.y);
}
let b = new B(200, 100);
console.log(b);
//结合原型链继承和借用构造函数继承组合起来实现的继承
特点:(call继承)
- 1.子类实例可以使用父类私有的属性和方法
- 2.父类私有的属性和方法都会变成子类实力私有的属性和方法
- 3.子类实例可以通过原型链访问和使用父类公有的属性和方法
- 4.子类的原型链上会存在一份多余的父类的私有属性和方法
方案四:call继承(借用构造函数继承)
//父类 function A(x) { this.x = x; this.seyHello = function (){ console.log("hello world"); } } A.prototype.getX = function () { console.log(this.x); } let a = new A(100); //子类 function B(y,x) { this.y = y; //this ==> b A.call(this, x);//this => b // this.x = x } B.prototype.getY = function () { console.log(this.y); } let b = new B(200, 100); console.log(b) // b = {y:200, x:100} //call继承(借用构造函数继承) //在子类构造函数中把父类构造函数当作普通的函数执行, //并且通过call方法把父类构造函数中的this替换成子类的实例(this), //这样相当于给子类实例设置了私有的属性和方法
-
特点:
- 1.只能继承父类私有的属性和方法(因为只是把父类构造函数当作普通函数执行了一次,跟父类的原型上的方法和属性没有任何关系)
-
2.父类的私有的属性和方法 都会变成子类私有的属性和方法