I’am trying to use some values from the “upper” function in the “inner” function:
function Load(el, script)
{
el.addEventListener('click',
function (e)
{
this.test = "testing";
script.apply(this, arguments);
}, false);
};
Load(document.getElementById("panel"),
function (e)
{
alert(test); // test is undefined
});
The above example doesn’t work, it says test is undefined.
But the following works:
function A(B)
{
this.test = "bla";
B.apply(this);
}
function B()
{
alert(test);
}
A(B);
What’s the difference? How can I make it work properly?
testis a property on the element at that point, so you need to reference it like that:You can test it here. The difference is that in the first example
thisrefers to theid="panel"element and the property is set there. In the second examplethisrefers to the global object, orwindow, sotestis a global variable that works when you go to access it.