聚合物内的Javascript函数不是函数错误
我在聚合物中定义了一个 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有看到完整的源代码示例,很难确定,但听起来您面临的问题与 JavaScript 没有将
this
推断为以相同方式调用实例方法的上下文有关例如 Java 就是这样做的。让事情变得更复杂的是,this
在您为点击侦听器创建的function
中不会具有预期值。解决这个问题的一种方法是使用箭头函数,因为它们不会重新定义执行上下文:
另一种选择是将
this
显式捕获到一个单独的变量中,然后在函数内使用该变量: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 thefunction
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:
Another alternative is to explicitly capture
this
into a separate variable and then use that variable inside the function: