首页 > 解决方案 > JavaScript: Is it possible to add arguments to a class extension?

问题描述

I am using Toxiclibs Verlet physics engine in JavaScript, and I would like to extend the VerletParticle2D class to create a custom object. It seems easy enough to add parameters and methods, but I wonder if my new class can have additional arguments. For example, VerletParticle2D takes one argument, which is a position vector.

Could I simply call the the new class with an additional argument, and pass it two vectors, and then define how the new argument is used in the added methods?

标签: javascriptclassinheritanceconstructorarguments

解决方案


你当然可以像这样扩展一个类:

class BaseClass {
  constructor(vector1) {
    this.vector1 = vector1;
  }
}

class MyClass extends BaseClass {
  constructor(vector1, vector2) {
    super(vector1);
    this.vector2 = vector2;
  }
}

然后用 . 创建一个新实例new MyClass(vector1, vector2)


推荐阅读