类的创建
- es6中采用class关键字进行类的创建
- es5中采用构造函数和原型对象的方式进行类的创建
//es6
class Singer {
//属性
constructor(sname, sage) {
this.sname = sname;
this.sage = sage;
}
// 方法
sing(song) {
console.log(this.sname + "演唱" + song);
}
}
var jn= new Singer ('Jennie');
nw.jn("solo");
console.log(jn);
//es5
function Singer(){
//属性
this.sname = sname;
this.sage = sage;
}
//方法
Singer.prototype.sing=function(song){
console.log(this.sname + "演唱" + song);
}
类的继承
- es6中使用extends关键字
class Son extends Father{}
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
// 计算加法
sum() {
return this.x + this.y;
}
}
// 继承用extends关键字
// 子类继承父类 子类可以使用父类的属性和方法,同时子类还能自己扩展的属性和方法
class Son extends Father {
// 子类要想使用父类的构造函数 必须用super()
constructor(x, y) {
// 把参数传到父类的构造器的参数里
// 这里是把子类的两个参数传到父类的构造函数里了
super(x, y); // 必须要写在第一行 也就是子类的this之前
this.x = x;
this.y = y;
}
less() {
return this.x - this.y;
}
}
var father = new Father(2, 3);
var son = new Son(5, 8);
// 子类自己的方法
console.log(son.sum());
// 子类继承了父类的加法
console.log(son.less());
- es5中:原型链继承、构造继承、组合继承、寄生式继承
/*
--原型链继承:子类的原型对象等于new一个父类的实例对象。
特点:基于原型链,既是父类的实例,也是子类的实例
缺点:无法实现多继承
*/
function Cat(){ }
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
/*--构造继承:使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类(没用到原型)
特点:可以实现多继承
缺点:只能继承父类实例的属性和方法,不能继承原型上的属性和方法。
*/
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
/*
--组合继承:通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用。
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
*/