简体   繁体   English

Object JavaScript 中的面向编程:如何从其他文件调用函数?

[英]Object Oriented Programming in JavaScript: how do I call functions from other files?

I have an app.js and another Highlight.js file.我有一个 app.js 和另一个 Highlight.js 文件。

In Highlight.js I have the following code:在 Highlight.js 我有以下代码:

export default class Highlights {
function foo() { alert(1) };
}

and in app.js I try to call the function foo as follows:在 app.js 中,我尝试调用 function foo,如下所示:

import highlight from './custom/HighlightingObjects.js';
highlight.foo();

But already at compling this via webpack I get an error message, that there is an unexpected token at:但是已经在通过 webpack 完成此操作时,我收到一条错误消息,表明在以下位置有一个意外令牌:

function foo() { alert(1) };

How can I handle this?我该如何处理?

foo is method of class. foo 是 class 的方法。 Instead反而

export default class Highlights {
  function foo() { alert(1) };
}

you need write你需要写

export default class Highlights {
  foo() { alert(1) };
}

You need to make the method static so it can be accessed directly like an object without calling the constructor.您需要创建方法 static 以便可以像 object 一样直接访问它,而无需调用构造函数。

export default class Highlights {
  static foo() {
    alert('...');
  }
}

Also that you don't use the function keyword in a class.此外,您不要在 class 中使用function关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM