variable “is not defined” error, why

旧时模样 提交于 2019-12-13 05:06:53

问题


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??


回答1:


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



来源:https://stackoverflow.com/questions/5700054/variable-is-not-defined-error-why

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