【问题标题】:Returning the proper child type when calling inherited parent method in JavaScript在 JavaScript 中调用继承的父方法时返回正确的子类型
【发布时间】:2017-07-21 21:33:51
【问题描述】:

假设我有这个父类Vector2 定义如下:

function Vector2 (x, y) {
  this.x = x;
  this.y = y;
}
Vector2.prototype.add = function(vec) {
  console.log(Reflect.getPrototypeOf(this));
  if (vec instanceof Vector2)
    return new Vector2(this.x + vec.x, this.y + vec.y);
  throw "This operation can only be performed on another Vector2. Recieved " + typeof vec;
};

Vector2 的扩展名为Size,它应该继承其父级的所有功能优势,并具有将xy 分别引用为wh 的附加能力,就像这样:

function Size(x,y) {
  this.x = x;
  this.y = y;
}
Size.prototype = new Vector2;
Size.prototype.constructor = Size;
Size.prototype._super = Vector2.prototype;
Object.defineProperties(Size.prototype, {
  'w': {
    get: function() {
      return this.x;
    },
    set: function(w) {
      this.x = w;
    }
  },
  'h': {
    get: function() {
      return this.y;
    },
    set: function(h) {
      this.y = h;
    }
  }
});

最后,我有一个代码 sn-p,它创建了两个 Size 的新实例,将它们加在一起,并尝试像这样从 w 属性中读取:

var s1 = new Size(2, 4);
var s2 = new Size(3, 7);
var s3 = s1.add(s2);
console.log(s3.w);
// 'undefined' because s3 is an instance Vector2, not Size

我如何修改Vector2add 方法来创建一个无论当前类的新实例而不是通用类?

【问题讨论】:

    标签: javascript oop inheritance


    【解决方案1】:

    您的 getter 代码中有错误:您需要使用 this 而不是 self

    然后你可以调用正确的构造函数:

    return new this.constructor(this.x + vec.x, this.y + vec.y);
    

    注意:您也可以使用vec.constructor,这完全取决于您在将 Size 对象添加到 Vector 对象时想要发生什么。对我来说,源对象(应用add 方法)确定返回对象的类似乎更直观。如果您认为添加的对象应该确定返回对象的类,请使用vec 而不是this

    【讨论】:

    • 你拒绝它很好。我只是测试并学到了一些东西。我为我的无知道歉。
    • 没问题。 ;-)
    【解决方案2】:

    我相信这可能就是您想要的。

    return new vec.constructor(this.x + vec.x, this.y + vec.y);

    使用传递给 add 方法的 constructor 创建返回的对象。

    您还错误地将this 传递给您的new Vector2( this, ... )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      相关资源
      最近更新 更多