0

I have defined a object in a js file:

myobj.js

MyObj={
  
  test: {
     value: {a: 10, b: 7},

     startTest: function(){
         var x = this.value.a;
         var y = this.value.b;
         return {x: x, y: y};
     }
  }
}

In another js file I call this object function:

other.js

mytest = MyObj.test.startTest //assign starTest function to mytest
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 myobj.js:

"this.value" is not defined in the line "this.value.a;"

Why?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mellon
  • 37,586
  • 78
  • 186
  • 264
  • possible duplicate of [Why I got "Undefined" error?](http://stackoverflow.com/questions/5699861/why-i-got-undefined-error) – Mat Apr 18 '11 at 08:05
  • No, it's different from my previous post – Mellon Apr 18 '11 at 08:05
  • This is personal preference: I don't like how you declare MyObj. I prefer "function MyObj(){ [...] }". Same for the startTest inner function: I Prefer "this.startTest = function(){ [...] }". Those are more "standard" ways. Refer to this StackOverflow question with a really good answer: http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript – dmarucco Apr 18 '11 at 08:07
  • Don't create a new question. Instead, update your original question with all the information. I mean obviously the code you posted there was not complete, otherwise you would have not get another error... – Felix Kling Apr 18 '11 at 08:12

1 Answers1

5

mytest = MyObj.test.startTest

This gives you a function without context. If you call this function directly then this is window.

You want to all test.startTest() so that this is test

An excellent guide on this

Raynos
  • 166,823
  • 56
  • 351
  • 396