首页 > 解决方案 > super.call(this) 的正确用法是什么

问题描述

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

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);”?

标签: javascriptclasscallsuper

解决方案


在 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


推荐阅读