JavaScript 错误:“不是构造函数”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5655367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:17:56  来源:igfitidea点击:

JavaScript error: "is not a constructor"

javascriptjquerydebuggingbackbone.jsunderscore.js

提问by Matthew

I'm using backbone.js along with jquery and underscore.js

我使用backbone.js 以及jquery 和underscore.js

Here's some of my code (it doesn't do anything yet). The strange thing is that upon hitting the url "/#users" there isn't an error. The only time the error happens is when I then click to go to a different hash and then click back to go to "/#users". Here's part of my code, with the line that receives the error toward the end Users = new Users();the error says "Users is not a constructor":

这是我的一些代码(它还没有做任何事情)。奇怪的是,在点击 url "/#users" 时没有错误。唯一发生错误的时间是当我单击以转到不同的哈希值,然后单击返回以转到“/#users”时。这是我的代码的一部分,最后收到错误的那一行Users = new Users();错误说“用户不是构造函数”:

var User = Backbone.Model.extend({
    url: function(){return 'api/user/id/' + this.id;}
});

var Users = Backbone.Collection.extend({
    model: User,
    url: function(){return 'api/users';},
    initialize: function() {
    }
});

var UsersView = Backbone.View.extend({
    initialize: function() {
        this.users = this.options.users;
        this.render();
    },

    render: function() {
        _(this.users).each(function(){
        //  $('#app').append('here');
        });

        var template = _.template($('#usersTemplate').text());

        $(this.el).html(template({users: this.users}));
        $('#app').html(this.el);
    }
});

var UserView = Backbone.View.extend({
    initialize: function() {
        this.user = this.options.user;
        this.render();
    },

    render: function() {

        var template = _.template("hello {{user.name}}");

        $(this.el).html(template({user: this.user.toJSON()}));
        $('#app').html(this.el);
    }
});

var Controller = Backbone.Controller.extend({
    routes: {
        'dashboard' : 'dashboard',
        'users' : 'showusers'
    },

    showuser: function(id) {
        UserList.fetch({
            success: function(){
                new UserView({user: User});
            },
            error: function(){
                alert('an error of sorts');
            }
        });
    },

    showusers: function() {
        Users = new Users();
        Users.fetch({
            success: function(Users) {
                new UsersView({users: Users});
            },
            error: function() {
            }
        });
    },

    dashboard: function() {
        Users = new Users;
        Users.fetch({
            success: function() {
                new UsersView({users: Users});
            },
            error: function() {
            }
        });
    }
});

$(document).ready(function(){
    var ApplicationController = new Controller;
    Backbone.history.start();
});

the accompanying html if you're curious:

如果您好奇,请查看随附的 html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Administration Panel</title>

    <!-- Framework -->
    <script src="/javascripts/jquery.min.js"></script>
    <script src="/javascripts/underscore.min.js"></script>
    <script src="/javascripts/backbone.js"></script>

    <!-- Application -->
    <script src="/javascripts/application.js"></script>

    <script id="usersTemplate" type="text/x-underscore-template">
        asdf
    </script>

</head>
<body>

<div>
<a href="#dashboard">Dashboard</a>
<a href="#users">Users</a>
<a href="#products">Products</a>
<a href="#orders">Orders</a>
<a href="#pages">Pages</a>
<a href="#settings">Settings</a>
</div>

<div id="app"></div>

</body>
</html>

回答by

newcan only be used with a Function as the operand.

new只能与作为操作数的函数一起使用。

new {}  // Error: ({}) is not a constructor

Check the type of Usersin context: it is nota Function when that exception is raised.

检查Users上下文中的类型:引发异常时它不是函数。

Happy coding

快乐编码



alert(typeof(Users))ought to do the trick. The result should be "function" to be usable as a constructor. Take note of what it is in the failing case, and see below for a reason.

alert(typeof(Users))应该做的伎俩。结果应该是可用作构造函数的“函数”。记下失败案例中的内容,并查看下面的原因。

One problematic scenario (for Users = new Users) may be: an object is constructed from the Function Usersand then the object (now not a Function/constructor) is assigned back to Usersso the next new Userswill go kaboom!(Look in both showusersand dashboard-- is that behavior reallyintended?)

一个有问题的场景(for Users = new Users)可能是:一个对象是从函数构造的Users,然后对象(现在不是函数/构造函数)被分配回,Users所以下一个new Users发生!(同时查看showusersdashboard- 这种行为真的是故意的吗?)

The 'correct' code is likely: var users = new Users; users.blahblah(...); that is, use a new local variable and do not overwritethe global Users variable/property.

“正确”的代码很可能:var users = new Users; users.blahblah(...); 也就是说,使用新的局部变量并且不要覆盖全局用户变量/属性。



The reason the error is only generated when "going back" to "#foobar" (a Fragment Identifier) is that no new page is actually loaded and thus the JavaScript is not reloaded and the current (now corrupt Users) is being used. kaboom!

仅在“返回”到“#foobar”(片段标识符)时才会生成错误的原因是实际上没有加载新页面,因此不会重新加载 JavaScript,并且Users正在使用当前(现在已损坏)。砰!

Excerpt from Fragment Identifier:

片段标识符摘录:

If the targeted element is located in the current document, a user agent may simply focus the targeted element without having to reload it ...

如果目标元素位于当前文档中,用户代理可以简单地聚焦目标元素而无需重新加载它......

回答by Basheer AL-MOMANI

I think its Syntax Error

我认为它的语法错误

this happened with me when I tried to return anonymous objectin my function

当我试图return anonymous object在我的函数中时,这发生在我身上

 var FalsEextension=false;
 ........
 ........
 return new  { FalsEextension, LargeFile };// wrong Syntax 

and the correct Syntax is

正确的语法是

 return { FalsEextension, LargeFile };

and you can use it like this

你可以像这样使用它

ObjectName.FalsEextension