【问题标题】:variable "is not defined" error, why变量“未定义”错误,为什么
【发布时间】:2011-04-18 08:00:34
【问题描述】:

我在一个js文件中定义了一个对象:

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

在另一个js文件中我调用了这个对象函数:

other.js

mytest = MyObj.test.startTest //assign starTest function to mytest
var a = mytest().x;
var b = mytest().y;

我的 index.html:

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

我在 myobj.js 中收到了来自 firebug 的错误:

this.value”在未定义 行“this.value.a;

为什么??

【问题讨论】:

  • Why I got "Undefined" error? 的可能重复项
  • 不,和我之前的帖子不一样
  • 这是个人喜好:我不喜欢你声明 MyObj 的方式。我更喜欢“函数 MyObj(){ [...] }”。 startTest 内部函数也一样:我更喜欢“this.startTest = function(){ [...] }”。这些是更“标准”的方式。请参考这个 StackOverflow 问题并给出一个非常好的答案:stackoverflow.com/questions/1595611/…
  • 不要创建新问题。相反,请使用所有信息更新您的原始问题。我的意思是显然你发布的代码不完整,否则你不会得到另一个错误......

标签: javascript-events javascript


【解决方案1】:

mytest = MyObj.test.startTest

这为您提供了一个没有上下文的函数。如果直接调用这个函数,那么this就是window

你想要所有test.startTest(),这样this就是test

An excellent guide on this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多