0

I have defined a object in a js file:

myobj.js

MyObj={
  test: {
     startTest: function(){
         var x = SOME_PROCESS_A;
         var y = SOME_PROCESS_B;
         return {x: x, y: y};
     }
  }
}

In another js file I call this object function:

other.js

var mytest = MyObj.test.startTest
var a = mytest.x;
var b = mytest.y;

my index.html:

<body>
 <script src="myobj.js"></script>
 <script src="other.js"></script>
</body>

I got the error from firebug in other.js, "mytest" is undfined in the line "var a = mytest.x;" Why??

Thank you,all. I got another "undefined" problem in the similar code, please check here

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mellon
  • 37,586
  • 78
  • 186
  • 264

3 Answers3

3

You have forgot to call the function:

var mytest = MyObj.test.startTest()
Eldar Djafarov
  • 23,327
  • 2
  • 33
  • 27
1

becouse mytest is a function object, and there are no properties defined in it.

you can either call it like

MyObj.test.startTest();

or rewrite your object something like:

MyObj={
  test: {
     startTest: function(){
         this.x = SOME_PROCESS_A;
         this.y = SOME_PROCESS_B;
         return {x: this.x, y: this.y};
     }
  }
}
Headshota
  • 21,021
  • 11
  • 61
  • 82
  • *"becouse mytest is a function object, it doesn't have properties"* Functions do have properties, and you can even add your own. Specifically in this case, though, this particular function doesn't have the `x` and `y` properties. – T.J. Crowder Apr 18 '11 at 07:48
  • yes I meant this particular function. I will correct my answer, thanks ;) – Headshota Apr 18 '11 at 07:56
  • Thank you, but I got another undefined error, here : http://stackoverflow.com/questions/5700054/variable-is-not-defined-error-why – Mellon Apr 18 '11 at 08:03
1

I think you meant to do

var mytest = MyObj.test.startTest(); //calls the function and returns the value to mytest

and not

var mytest = MyObj.test.startTest;//assigns the function to mytest
JohnP
  • 49,507
  • 13
  • 108
  • 140
  • Thank you. but I got another undefined error, here http://stackoverflow.com/questions/5700054/variable-is-not-defined-error-why – Mellon Apr 18 '11 at 08:02
  • @Mellon, you shouldn't post a new question. It will likely be closed as duplicate. Update this question – JohnP Apr 18 '11 at 08:03