聚合物内的Javascript函数不是函数错误

发布于 2025-01-13 17:39:54 字数 476 浏览 2 评论 0原文

我在聚合物中定义了一个 JavaScript 函数,如下所示: myTest(arg) {}

在此函数内,根据某些条件,我想将聚合物模板中定义的按钮的 onclick 更改为一些其他功能。为此,我正在执行 document.getElementById('myButton').onclick = function() {myTest('someArg')};

我遇到的问题是,当上面的行被调用时我收到错误

未捕获类型错误:myTest 不是函数。

如果我在声明函数时尝试使用 function 关键字,编译器会抱怨

意外的令牌。需要构造函数、方法、访问器或属性。

更改按钮的 onclick 函数的正确语法是什么?

I have a javascript function defined in polymer as such:
myTest(arg) {<do stuff here>}

Inside this function, based on some conditions, I want to change the onclick of a button defined in the polymer template to some other function. For this I'm doing document.getElementById('myButton').onclick = function() {myTest('someArg')};

The problem I'm having is that when the above line gets invoked I'm getting an error

Uncaught TypeError: myTest is not a function.

If I try to use the function keyword when declaring the function the compiler complains with

Unexpected token. A constructor, method, accessor, or property was expected.

What's the correct syntax to for changing the button's onclick function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怎樣才叫好 2025-01-20 17:39:54

如果没有看到完整的源代码示例,很难确定,但听起来您面临的问题与 JavaScript 没有将 this 推断为以相同方式调用实例方法的上下文有关例如 Java 就是这样做的。让事情变得更复杂的是,this 在您为点击侦听器创建的 function 中不会具有预期值。

解决这个问题的一种方法是使用箭头函数,因为它们不会重新定义执行上下文:

document.getElementById('myButton').onclick = () => { this.myTest('someArg') };

另一种选择是将 this 显式捕获到一个单独的变量中,然后在函数内使用该变量:

var self = this;
document.getElementById('myButton').onclick = function() { self.myTest('someArg') };

It's hard to say for sure without seeing the the full source code example, but it sounds like the problem you're facing is related to JavaScript not inferring this as the context for calling instance methods in the same way that e.g. Java does. To make things more complicated, this wouldn't have the expected value inside the function that you create for the click listener.

One way around that would be to use an arrow function since they aren't redefining the execution context:

document.getElementById('myButton').onclick = () => { this.myTest('someArg') };

Another alternative is to explicitly capture this into a separate variable and then use that variable inside the function:

var self = this;
document.getElementById('myButton').onclick = function() { self.myTest('someArg') };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文