继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法,或子类从父类
继承方法,使得子类具有父类相同的行为。
1.call继承
function Father(uname, age) {
// this指向fu构造函数实例
this.uname = uname
this.age = age
}
Father.prototype.sing = function () {
console.log('sing')
}
function Son(uanme, age, score) {
Father.call(this, uanme, age)
// this指向子构造函数实例
this.score = score
}
var s = new Son('ldh', 23, 1000)
console.log(s)
所以我们可以看到call继承是不能继承原型的方法和属性的,那么如果我们想要继承父类的属性和方法可以使用原型继承
2原型继承
function Father(uname, age) {
// this指向fu构造函数实例
this.uname = uname
this.age = age
}
Father.prototype.sing = function () {
console.log('sing')
}
function Son(score) {
// this指向子构造函数实例
this.score = score
}
Son.prototype = new Father()
var s = new Son('ldh', 23, 1000)
console.log(s)
我们可以看到原型继承是可以继承到父类的属性和方法的,但是原型继承也是有缺点的。当父类原型的属性和方法发生改变的时候会影响子类的构造函数,所以我们可以用到组合继承
3组合继承
function Father(uname, age) {
// this指向fu构造函数实例
this.uname = uname
this.age = age
}
Father.prototype.sing = function () {
console.log('sing')
}
function Son(uname, age, score) {
Father.call(this, uname, age)
// this指向子构造函数实例
this.score = score
}
Son.prototype = new Father()
var s = new Son('ldh', 23, 1000)
console.log(s)
组合继承 call继承+原型继承,但是组合继承也是有缺点的 父类自身的属性和方法 继承了两次
原型式继承:对一个对象进行浅克隆创建另一个对象,同时继承该对象的原型属性
缺点: 浅克隆 会受污染
4 es6中新增加了类的概念,可以使用class声明一个类。之后以这个类实例对象,类抽象了对象的公共部分,它泛指某一大类(class)对象特指某一个,通过类实例化一个具体的对象
// 1. 创建类 class 创建一个类
class Star {
// 类的共有属性放到 constructor 里面 constructor是 构造器或者构造函数
constructor(uname, age) {
this.uname = uname;
this.age = age;
} //------------------------------------------->注意,方法与方法之间不需要
添加逗号
sing(song) {
console.log(this.uname + '唱' + song);
}
}
// 2. 利用类创建对象 new
var ldh = new Star('刘德华', 18);
console.log(ldh); // Star {uname: "刘德华", age: 18}
ldh.sing('冰雨'); // 刘德华唱冰雨
// class Father {
// constructor(name, age) {
// this.name = name
// this.age = age
// }
// say() {
// console.log(say);
// }
// }
// class Son extends Father {}
// //利用类创建对象 new
// var s = new Son('刘德华', 18);
// console.log(s);
// 子类使用super关键字访问父类的方法
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
//子元素继承父类
class Son extends Father {
constructor(x, y) {
super(x, y); //使用super调用了父类中的构造函数
}
}
var son = new Son(1, 2);
son.sum(); //结果为3