【问题标题】:Including Javascript file inside another Javascript file在另一个 Javascript 文件中包含 Javascript 文件
【发布时间】:2023-03-18 21:54:01
【问题描述】:

我有两个类,例如 ParentClassChildClass 在 2 个单独的文件中。我直接在ChildClass 中调用一个函数,并且我想在调用ChildClass 时动态包含ParentClass。我想要使用任何外部库或包,例如jQueryrequire.js 等。我也想要使用ES6nodejs requirehere 所说,因为浏览器兼容性问题。


这是我的文件的样子,

parentclass.js

var ParentClass = function(param1, param2) {
    // Class related code here
};

ParentClass.prototype.parentClassFunction = function() {
     // Code for the function here...
};

childclass.js

var ChildClass = function(param1, param2) {
    // Some class related code here...

    this.parentClassFunction();

    // Some other code...
};

ChildClass.prototype = Object.create(ParentClass.prototype);

HTML 文件

.....
<head>
  ...
  <script src="childclass.js"></script>
  ...
</head>
<body>
  ...
  <script>
    var value = new ChildClass(10, 20);
  </script>
  ...
</body>

有什么方法可以实现吗?感谢您的帮助。

提前致谢。 :)

注意:我简要了解了thisthisthis 的问题。

【问题讨论】:

  • 也许在中写一个脚本stackoverflow.com/questions/18784920/…
  • 或者使用像 webpack 这样的打包工具
  • @BalajMarius 我在 标签中导入了脚本。我会以更清晰的方式编辑问题。
  • @bharadhwaj “..我想在调用 ChildClass 时动态包含 ParentClass”是什么意思
  • @BalajMarius 我的意思是,当ChildClass 被调用时,它使用ParentClass 中的函数,但我不想在HTML 中手动添加每个依赖的js 文件,而是想动态选择它需要的时候。希望清楚。

标签: javascript


【解决方案1】:

最好的选择是将所有文件与预编译器或类似的东西捆绑在一起。

在您的 childclass.js 中,您应该使用 require('parentclass.js') 或 import 使用 Browserify 之类的东西来自动解决依赖关系。

这里有一些链接: - http://browserify.org/ - https://webpack.github.io/

【讨论】:

    【解决方案2】:

    如果你使用 ES6 特性,你可以使用 import:

    例如:

    import { Childclass } from '/path/to/childclass';

    这里是导入的文档:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

    【讨论】:

    • 我在问题中提到,由于浏览器兼容性问题,我想要 ES6。
    • 对不起
    • 为什么你不尝试使用commonjs来拥有像nodejs那样的require:requirejs.org/docs/start.html
    • 我正在尝试创建一个要求最低的库,所以我不想增加包的开销。这就是原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    相关资源
    最近更新 更多