tags:

views:

17

answers:

1

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(){
            }

            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>
A: 

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.

CharlesLeaf
Please show how to do it.
shivesh
`this` does exist: at the moment the event fires, it is set to element `textarea#text`.
Marcel Korpel
@shivesh something like this? `var self = this; txt.addEventListener("keyup", function(){ self.Foo(); }, true);`@Marcel That's not completely true in this scenario, most JS libraries make sure that `this` is the element, but in native javascript that behaviour is not 100% cross browser proof.
CharlesLeaf
That's right, but the OP is using Firefox and `addEventListener`.
Marcel Korpel