首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在方法中缩小此对象的特定成员范围

在方法中缩小此对象的特定成员范围
EN

Stack Overflow用户
提问于 2020-09-14 06:46:07
回答 1查看 18关注 0票数 0

我想在类中调用一个特定的函数,但只允许调用该函数,前提是当前设置了可为空的属性。

我拥有的代码如下:

代码语言:javascript
复制
class VisualComponent {
  public fallback_color: p5.Color;
  public image: p5.Image | null = null;

  public constructor(color:p5.Color) {
    this.fallback_color = color;
  }

  public draw(p:p5) {
    if (this.image) {
      this.draw_image(p);
    } else {
      p.fill(this.fallback_color);
      p.rect(0,0,100,100);
    }
  }

  private draw_image(p:p5) {
      // this has potentially a bit more logic in it or
      // is different in subclasses
      p.drawImage(this.image);  // <-- Error this.image is possibly null
  }
}

我希望上面的代码能让你明白这一点。我想告诉'draw_image‘函数,只有在当前设置了this.image时才能调用它。

代码语言:javascript
复制
let visual = new VisualComponent(p.color(0,0,255));
visual.draw(); // <-- draws the color
visual.image = __some_image__;
visual.draw(); // <-- draws the image

所以我假设我需要一些类似如下的typeguards:Keep track of state in class instance

代码语言:javascript
复制
type VisualComponentWithImage = VisualComponent & {image:p5.Image}; 

class VisualComponent {
  ...
  public has_image(): this is VisualComponentWithImage {
    if (this.image) return true;
    return false;
  }

  // well, now I can use the typeguard here but the 'draw_image' function
  // is still not narrowed down obviously
  public draw(p:p5) {
    if (this.has_image()) {
      this.draw_image(p);
    } else {
      p.fill(this.fallback_color);
      p.rect(0,0,100,100);
    }
  }

  // I expect now to do the following
  private draw_image(p:p5) : this if VisualComponentWithImage  {
    // and in here this should be of type VisualComponentWithImage  
    // as well as any call to this prior to asserting that image exists should be a type error
  }
  ...
}

我在Typescript文档中做了一些尝试:

https://www.typescriptlang.org/docs/handbook/utility-types.html

我认为ThisType<T>可能是正确的方向,但是我不知道如何在已经存在的类上下文中使用它。(它似乎用于示例中动态创建的类)

在我看来,https://www.typescriptlang.org/docs/handbook/decorators.html装饰者似乎可以解决这个问题。但老实说,它们看起来有点吓人,使用起来也不是很整洁。整洁毕竟是我想要的。

我目前的解决方案是将'draw_image‘函数从类中分离出来,如下所示:

代码语言:javascript
复制
function draw_image(this: VisualComponentWithAnimation, p:p5) {
    p.drawImage(p);
}

我在'draw‘函数中这样调用它

代码语言:javascript
复制
if (this.has_image()) {
  draw_image(this, p);
}

虽然理想情况下,我希望将该函数放在类中,只是为了让它属于它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-14 06:51:40

就在提出问题的过程中,a有了解决的想法。或者更确切地说,我尝试了一些愚蠢的东西,结果证明是有效的。

我只是在类中移动了draw_image(this: VisualComponentWithAnimation, p:p5) ...,仅此而已。

我从来没有想过我可以在一个类中像这样‘覆盖’this。但它完美地缩小了函数内部的'this‘范围,像任何其他类方法图像一样被调用(没有显式地放入"this"),并且如果没有设置’this.draw_image(p);‘,也不允许调用。

我猜有时写一篇文章也有助于解决一个问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63876251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档