ES6类中的继承和原型链

时间:2018-11-26 10:15:16

标签: javascript ecmascript-6 es6-class

我有以下课程

class Polygon {
   constructor(height, width) {
      this.height = height;
      this.width = width;
   }
}



class Square extends Polygon {
   constructor(sideLength) {
      super(sideLength, sideLength);
   }

   area() {
      return this.height * this.width;
   }

   sideLength(newLength) {
      this.height = newLength;
      this.width = newLength;
   }
}

然后创建一个Square类的实例

var square = new Square(2);

我的期望是在方形对象中(直接在方形对象中而不是在其原型中)找到areasideLength方法。我以不同的方式在__proto__对象中找到它们。 result

我不明白为什么会这样。 您可以使用构造函数而不是类来“翻译”相同的代码吗?也许我会以这种方式更容易理解这一点...

1 个答案:

答案 0 :(得分:3)

在类中定义的方法将转换为protoType方法,以使该类的所有实例共享同一方法。您的案例的功能组件版本为

function Polygon(height, width) {
    this.height = height;
    this.width = width;
}


function Square(sideLength){
   Polygon.call(this, sideLength);
}

Square.prototype.area = function() {
   return this.height * this.width;
}

Square.prototype.sideLength(newLength) {
  this.height = newLength;
  this.width = newLength;
}

但是,如果您在类构造函数中定义函数或使用arrow functions,则它们将属于类实例,例如

class Polygon {
   constructor(height, width) {
      this.height = height;
      this.width = width;
   }
}



class Square extends Polygon {
   constructor(sideLength) {
      super(sideLength, sideLength);
      this.getArea = function() {
         return this.height * this.width;
      }
      this.sideLengthWithBind = this.sideLength.bind(this);
   }

   area =() =>{
      return this.height * this.width;
   }

   sideLength(newLength) {
      this.height = newLength;
      this.width = newLength;
   }
}

const square = new Square(5);

console.log(square);