JS的继承

401 阅读1分钟
1.基于原型的继承
2.基于class的继承

继承的基本概念:继承指一个对象直接使用另一对象的属性和方法

继承的作用:继承是面向对象语言的重要机制。借助继承,可以扩展原有的代码,应用到其他程序中,而不必重新编写这些代码。

1.基于原型的继承

function Parent(name1){
  this.name1 = name1
}
Parent.prototype.pMethod = function(){
  console.log(this.name1)
}

function Child(name2, name1){
    Parent.call(this, name1) 
    this.name2 = name2
}
Child.prototype.__proto__ = Parent.prototype 
Child.prototype.cMethod = function(){
    console.log(this.name2)
}

2.基于类的继承

extends关键字主要用于类声明或者类表达式中,以创建一个类,该类是另一个类的子类。其中constructor表示构造函数,一个类中只能有一个构造函数,有多个会报出SyntaxError错误,如果没有显式指定构造方法,则会添加默认的 constructor方法,使用例子计算一个长方形的面积和周长:

class Rectangle {
    // constructor
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    getArea() {
        return this.height * this.width;
    }
}
const rectangle = new Rectangle(10, 20);
console.log(rectangle.getArea());
// 输出 200

-----------------------------------------------------------------
// 继承
class Square extends Rectangle {

  constructor(length) {
    super(length, length);
    
    // 如果子类中存在构造函数,则需要在使用“this”之前首先调用 super()。
    this.name = 'Square';
  }
//下面的函数可省略
   getArea() {           
    return this.height * this.width;
  }
}
const square = new Square(10);
console.log(square.getArea());
// 输出 100

这样我们子类Square就继承了父类Rectangle的属性和方法。