Javascript Function Falling Out Of Scope? "x Is Not A Function" "x Is A "" "
Solution 1:
action
in the inline event handler refers to the action
property of the form containing the clicked element. It shadows your global action
function, use a different name for the function, or rather use addEventListener
to attach events. You can see the value in the snippet.
functionfoo(a) {
console.log(a);
}
<form><buttontype="button"onclick="foo(action);">
Click
</button></form>
The reason behind this is, that the code in an inline handler is scoped to the event target element using with (event.target) {...}
(or similar internal scoping mechanism), and when the given variable (property actually) is not found from the element itself, with
looks up the ancestor elements until the property is found. If it's not found from the elements, the last object to search is window
, and this way it finds the global function which was meant to be executed, providing there wasn't naming conflict on the way up to window.
Post a Comment for "Javascript Function Falling Out Of Scope? "x Is Not A Function" "x Is A "" ""