【问题标题】:What is the proper use of super.call(this)super.call(this) 的正确用法是什么
【发布时间】:2021-01-06 16:48:09
【问题描述】:

我有一个类函数(不是我最初开发的)...

function Project()
{
  Project.super.call(this);
  // this._some_var = null;
  /* other initial vars */
  ...
  return DefensiveObject.create(this); // see comment below
}

function initialize()
  {
     //*******Initialize Project************
  }
  ...

return Project;

此函数是运行节点 main.js 所包含的名为“Project.js”的模块的一部分。

  return DefensiveObject.create(this); // not return Object.create(this)

DefensiveObject 是一个防止对象获取或 设置类中未明确设置的属性。

main.js 调用驻留在我的 Project 类中的 Project.initialize()。

我的问题是为什么需要调用“Project.super.call(this);”?

【问题讨论】:

  • 这是在class Project { .. } 块内吗?构造函数应该命名为constructor,与类不一样。
  • 默认没有Project.super属性。你用的是什么继承框架?阅读其文档以了解如何使用它。为什么不直接使用标准 ES6 classes 和 super()
  • "return Object.create(this);" - 不要那样做。构造函数不应该return 任何东西。
  • 感谢您的更新,但这仍然不足以回答。请提供完整代码作为完整的minimal reproducible example
  • super.call 是脆弱的,正如专家们向我们展示的那样。 ;)(抱歉,忍不住)

标签: javascript class call super


【解决方案1】:

在 Javascript 中,保留字 super 在 ES6 类中用于引用子类的父类,使用它来引用函数是没有意义的。

请阅读这篇解释 super 用法的文章

https://jordankasper.com/understanding-super-in-javascript/

这篇中等文章也可以帮助你 https://medium.com/beginners-guide-to-mobile-web-development/super-and-extends-in-javascript-es6-understanding-the-tough-parts-6120372d3420

【讨论】:

    【解决方案2】:

    Project.super.call(this) 行是一种允许在“Disposable”类(未包含在原始问题中)中使用 dispose 方法的方法,该方法允许从内存中清理代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 2011-04-15
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多