tags:

views:

46

answers:

3

I am trying to call the function MyMethod from within a object but none of the syntax below works. There must be a really obvious error below but I can't see it.

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>

   <script type="text/jscript">

     function MyObject() {

       //how do I get one of these to work??
       this.MyMethod; //does not work
       this.MyMethod(); //does not work either
       MyMethod(); //does not work either

       this.MyMethod = function () {
         alert('It works');
       }
     }

     var test = new MyObject();

   </script>

</head>
<body>

</body>
</html>
+3  A: 

There are two main problems

  1. The MIME type is text/javascript, not text/jscript
  2. You are defining the method after you try to call it

So:

  function MyObject() {
    this.MyMethod = function () {
      alert('It works');
    }
    this.MyMethod(); //does not work either
  }

  var test = new MyObject();
David Dorward
+1  A: 

you have put the call to the private method inside the constructor of the javascript class. in that point the functions are not yet initialized

but if you initialize the object like so:

var test = new MyObject(); 

and then do this:

test.myMethod();

it will work.

guy schaller