Javascript 原型函数和 SVG setAttribute(onclick)
尝试使用 svg onClick 来调用原型函数。
通常要调用原型函数,我只会这样做。(functionName),但是当我将其放入 .setAttribute(onclick, "this.(functionName)")
时,它无法识别原型函数。有人有这方面的经验吗?
如果上面的内容不清楚,这是它的基本要点......
function myobject(svgShape) {
this.svgshape.setAttribute(onclick, 'this.doSomething()');
}
myobject.prototype.doSomething = function() {
alert("works");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
三件事可能会有所帮助:
1)首先,我认为您在
myobject
函数顶部缺少这一行:我假设这只是发布问题的错误并已插入该行以下。
2) 通常,当您使用 Prototype(或任何现代库)时,您不会使用字符串进行回调,而是使用函数。此外,您通常使用库的包装器来分配处理程序
addEventListener
/attachEvent
(observe
,在 Prototype 的情况下)而不是旧的 DOM0 属性。所以:3) 但是 JavaScript 没有方法(它并不真正需要它们),它只有函数,所以上面的内容不能确保
this
(调用的上下文)设置正确。对于 Prototype,您可以使用bind
来设置上下文:(或者你可以使用你自己的闭包来做到这一点。
bind
的优点是闭包处于一个非常受控的环境中,因此不会关闭你不关心的东西)现在,我从未使用 Prototype 进行过任何 SVG 编程,因此如果
observe
由于某种原因不起作用,您可以尝试直接分配给onclick
反射属性:我仍然在那里使用
bind
,以便this
具有正确的值。我贫血的小博客中的这些帖子提供了对上述内容的更多讨论:
Three things that may help:
1) First off, I think you're missing this line from the top of your
myobject
function:I'm assuming that was just an error posting the question and have inserted that below.
2) Normally when you're using Prototype (or any modern library), you don't use strings for callbacks, you use functions. Also, you normally assign handlers using the library's wrapper for
addEventListener
/attachEvent
(observe
, in Prototype's case) rather than the old DOM0 attribute thing. So:3) But JavaScript doesn't have methods (it doesn't really need them), it just has functions, so the above won't ensure that
this
(the context of the call) is set correctly. With Prototype you'd usebind
to set the context:(Or you can use your own closure to do it. The advantage of
bind
is that the closure is in a very well-controlled environment and so doesn't close over things you don't want kept around.)Now, I've never done any SVG programming with Prototype, so if
observe
doesn't work for some reason, you might try directly assigning to theonclick
reflected property:I'm still using
bind
there so thatthis
has the correct value.These posts from my anemic little blog offer more discussion of the above:
this