2

我正在尝试使用 QUnit 进行简单的测试,但由于某种原因它无法找到我的函数。我在做一些根本错误的事情吗???

测试.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title></title>
  <script type="text/javascript" src="qunit-git.js"></script>
  <script type="text/javascript" src="jquery.min.js"></script>
  <script type="text/javascript" src="code.js"></script>
  <script type="text/javascript" src="test.js"></script>
  <link rel="stylesheet" type="text/css" href="qunit-git.css" media="screen"/>
</head>
<body>
<h1 id="qunit-header">QUnit Test Suite</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
</body>
</html>

测试.js

test('Blah blah', function() {
  ok(mytest(), 'foo bar'
  );
});

代码.js

$(document).ready(function() {
  var mytest = function() {
    return true;
  }
});

--> “在测试 #1 中死亡:mytest 未定义...”

4

1 回答 1

3

mytest()在函数内部声明ready(),因此具有函数作用域。因此,从ready函数外部无法访问它。您的测试假定它具有全局范围。

在块作用域中声明的变量和函数被“提升”到最近的函数作用域的顶部,如果没有在函数中声明,则被“提升”到全局作用域。

编辑

最终,我会说代码结构不正确。ready 函数用于运行仅在文档准备好时才需要运行的东西。

用更强类型的语言来思考。你会在 a Page.Load()or Window.Load()or中定义一个函数吗Application.Init()?不,您会在类级别声明它并像那样访问它。

以这种方式考虑您的 JavaScript 代码。如果要缩小其范围,请在另一个类中声明它。

于 2011-06-17T18:36:53.697 回答