【问题标题】:Inheritance and the prototype chain in ES6 classesES6 类中的继承和原型链
【发布时间】:2018-11-26 10:15:15
【问题描述】:

我有以下课程

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__ 对象中找到了它们。

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

【问题讨论】:

  • 这是拥有类的要点之一 - 让对象共享一个公共的单个内部原型对象(此处为 Square.prototype,与 square.__proto__Object.getPrototypeOf(square) 相同) - 而不是每个新对象都有自己的方法
  • ES6 仍然使用原型链,类只是语法上的糖。编辑:请阅读stackoverflow.com/questions/36419713/…了解更多信息。

标签: javascript ecmascript-6 es6-class


【解决方案1】:

类中定义的方法被转换为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);

【讨论】:

  • 那么,如果我说类中定义的每个函数都成为使用该类创建的实例的原型对象的一部分,我错了吗?
  • 是的,除非函数是在类构造函数中定义的,如this.getArea = function() { return this.height * this.width; } 或使用箭头函数如area = () => {}
  • 哦,这是一个非常重要的说明。谢谢!
  • 很高兴能帮上忙
  • @ShubhamKhatri:类属性不限于箭头函数。 area = function() {}area = 42; 也会在对象本身上创建 area
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多