在eventListener上应用不起作用

时间:2010-07-17 03:09:12

标签: javascript events

我试图在“内部”函数中使用“upper”函数中的一些值:

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
    });

上面的示例不起作用,它说test未定义。

但是以下工作:

function A(B)
{
  this.test = "bla";
  B.apply(this);
}
function B()
{
  alert(test);
}
A(B);

有什么区别?我怎样才能让它正常工作?

3 个答案:

答案 0 :(得分:3)

test是该点元素的属性,因此您需要像这样引用它:

Load(document.getElementById("panel"),
function (e)
{
    alert(this.test); // "testing"
});

You can test it here。不同之处在于,在第一个示例中,this引用了id="panel"元素,并且在那里设置了属性。在第二个示例中,this引用全局对象,或window,因此test是一个全局变量,当您访问它时它会起作用。

答案 1 :(得分:1)

在第二个示例中,当您致电A()时,this引用window对象,因为这是A()运行的范围。所有全局变量也属于window对象,因此在该上下文中,testthis.testwindow.test都是相同的实体。

但是,在第一个示例中,this指的是调用处理程序的元素,因此this.test(已定义)与"#panel".test相同但不同于testwindow.test(未定义)。

答案 2 :(得分:0)

你应该接受Nick Craver的回答,我只是在这里用更多代码澄清:

function Load(el, script)
{
    el.addEventListener('click',
        function (e)
        {
            this.test = "testing";  // sets el.test="testing" ('cos this==el)
            script.apply(this, arguments);
        }, false);
};

Load(document.getElementById("panel"),
    function (e)
    {
        alert(test); // alerts window.test, not el.test
    });
function A(B)
{
  this.test = "bla"; // sets window.test="bla" ('cos this==window)
  B.apply(this);
}
function B()
{
  alert(test); // alerts window.test
}
A(B);