Why did I get “Undefined” message?

醉酒当歌 提交于 2019-12-23 04:47:20

问题


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


回答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



回答2:


You have forgot to call the function:

var mytest = MyObj.test.startTest()



回答3:


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};
     }
  }
}


来源:https://stackoverflow.com/questions/5699861/why-did-i-get-undefined-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!