https://blog.nowcoder.net/n/5b18d18a62fb47079050a041cb3eb73e
ES5实现继承
function Rectangle(length,width){
this.length = length;
this.width = width;
}
Rectangle.prototype.getArea = function(){
return this.length*this.width;
}
function Square(length){
Rectangle.call(this,length,length);
}
Square.prototype = Object.create(Rectangle.prototype,{
constructor: {
value:Square,
enumerable:true,
writable:true,
configurable:true
}
});
var square = new Square(3)
console.log(square.getArea()) //9
console.log(square instanceof Square) //true
console.log(square instanceof Rectangle) //trueES6类实现继承
class Rectangle{
constructor(length,width){
this.length = length;
this.width = width;
}
getArea(){
return this.length*this.width;
}
}
class Square extends Rectangle{
constructor(length){
super(length,length);
}
}
var square = new Square(3);
console.log(square.getArea()) //9
console.log(square instanceof Square) //true
console.log(square instanceof Rectangle) //truesuper()方法可以访问基类的构造函数。
继承自其他类的类被称作派生类,派生类指定了构造函数则必须要调用super(),否则程序会报错,如果不使用构造函数,则创建新的类实例会自动调用super()并传入所有参数。
super使用说明:
1.只可以在派生类中使用super,如果在非派生类(不使用extends声明的类)使用会导致程序抛出错误。
2.在构造函数访问this之前一定要先调用super(),它负责初始化this。
3.如果不想调用super,则是让类的构造函数返回一个对象。
如果在派生类中定义一个与基类中同名的方法,方***将其覆盖会重新定义这个方法的功能。
class Square extends Rectangle{
constructor(length){...}
getArea(){ return this.length*this.length}
//会覆盖并遮蔽Rectangle.prototype.getArea()方法
//getArea(){ return super.getArea(); }
//如果想要调用基类中的该方法,可以调用super.getArea();
}静态成员继承:如果基类有静态成员,这些静态成员在派生类中也可以使用。
每个类都有三个部分:第一个部分时构造函数内的,供实例化对象复制用的;第二个部分是构造函数外的,直接通过点语法添加的,这是供类使用的,实例化对象是访问不到的,第三部分是类的原型中的,实例化对象可以通过其原型链间接访问到,为供所有实例化对象所共用的

京公网安备 11010502036488号