【问题标题】:javascript reference error while trying to implement mvc尝试实现 mvc 时出现 javascript 参考错误
【发布时间】:2017-01-25 05:36:18
【问题描述】:

嘿,我是 javascript 新手,我正在尝试创建一个简单的 mvc 应用程序。

这是我的 model.js:

     function Question(question,hint,answer){

        this.question = question;
        this.hint = hint;
        this.answer = answer;
    }

这是我的 view.js:

    function view(modelList){
    this.modelList = modelList;

    }

view.prototype.show = function(){
   var length  = this.modelList.length;
   for(var i=0;i<length;i++){
         alert(this.modelList[i].question);
         console.log(this.modelList[i].question);
   }
};

这是我的 controller.js:

    function controller(modelList){
      this.view = new view(modelList);
    }


controller.prototype.show = function(){
     this.view.show();
};

这是我的 index.html:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="app.js"></script>
  <script src="controller.js"></script>
  <script src="model.js"></script>
  <script src="view.js"></script>
</head>

<body>
</body>


</html>

当我在浏览器上运行 index.html 时,我收到如下错误:

jQuery.Deferred 异常:模型未定义 ReferenceError:模型未定义 在 HTML 文档。 (file:///D:/Javascript/MVC/app.js:3:23) 在 j (https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:29948) 在 k (https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:30262) 未定义

和

> Uncaught ReferenceError: model is not defined
    at HTMLDocument.<anonymous> (app.js:3)
    at j (jquery.min.js:2)
    at k (jquery.min.js:2)

谁能告诉我哪里错了??

谢谢你

编辑:

这是我的 app.js:

    $(function(){

     var model1 = new model("question","hint","answer");
     var model2 = new model("question2","hint2","answer2");

     var modelList = {model1,model2};

     var controller = new controller(modelList);
     controller.show();


});

【问题讨论】:

  • 我刚刚添加了 app.js
  • 不,还是同样的错误
  • 我强烈建议您将所有代码粘贴到 jsfiddle.net 并在那里运行(在我们的帮助下)。然后在解决问题后粘贴回单个文件。这种来回的进展非常缓慢。
  • jsfiddle.net/weeuedub这里是我上传代码的地方,请查看

标签: javascript jquery


【解决方案1】:

这里是固定版本:https://jsfiddle.net/weeuedub/1/

  1. 添加了 jQuery 作为依赖项(您不需要在自己的应用程序中这样做)。
  2. 将您的 controller 类重命名为 Controller。

问题出在这一行:

var controller = new controller(...);

因为你使用的是变量名“controller”,它会覆盖上面声明的“controller”函数。

按照惯例,请尝试以大写字母开头的类命名。

更新:https://jsfiddle.net/weeuedub/2/

您将modelList 分配为{ model1, model2 },这不是您可以通过获取length 来迭代的数组。这是一个等同于:{ model1: model1, model2: model2 } 的对象。这是浏览器尚未广泛支持的 ES6 语法,我认为这只是您的拼写错误。解决方法是将其更改为 [ model1, model2 ] 以获取数组。

【讨论】:

  • 在哪里可以查看 jsfiddle 中的控制台!提示框出现了吗??
  • 这是你浏览器的常规 JS 控制台。
  • 谢谢你真的很有帮助
【解决方案2】:

你的 model.js 定义了一个Question function

您应该将其更改为

function model(question,hint,answer){}

或将实例化更改为Question。

var model1 = new Question("question","hint","answer");
var model2 = new Question("question2","hint2","answer2");

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    相关资源
    最近更新 更多