开发者

Event triggering inside prototype

When I try to call "Test" function I get an error.

How to fix that? (no jquery!)

Browser:firefox

error:

TypeError: this.Test is not a function

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Untitled Document</title>
        <script type="text/javascript">



            MyClass = function(){
            开发者_Python百科}

            MyClass.prototype = {

                Init: function(){
                    var txt = document.getElementById("text");

                    if (txt.addEventListener) {
                        txt.addEventListener("keyup", this.Foo, true)
                    }


                },

                Foo: function(){
                    this.Test();
                },

                Test: function(){
                    alert('OK');
                }


            }
            window.onload = function(){
                obj = new MyClass;
                obj.Init();
            }
        </script>
    </head>
    <body>
    <textarea id="text" rows="10">
    </textarea>
    </div>
</body>


It's because you reference this.Foo as the event, what actually happens is that it copies that function out of the object scope, ergo this does not exist. What most people do is use an anonymous function / wrapper around the event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜