2016-04-24 25 views
2

为什么我看不到问题?有人可以帮我吗? 我知道这是个很愚蠢的问题..但我没有看到它..未捕获ReferenceError xxx未定义

执行:var xxx = new User(),我总是得到这样的:

ready! 
VM1507:1 Uncaught ReferenceError: User is not defined(…) 

对不起问..

$(function() { 
    console.log("ready!"); 

    function User() { 
     this.badgeVervalDatum = null; 
     this.bijNaam = null; 
     this.contactVia = null; 
     this.email = null; 
     this.familieNaam = null; 
     this.gsm = null; 
     this.id = null; 
     this.middleNaam = null; 
     this.postcode = null; 
     this.rkNummer = null; 
     this.sanBekw = null; 
     this.straat = null; 
     this.voorNaam = null; 
     this.volledigNaam = null; 
     this.woonplaats = null; 
     this.timeCreated = 0; 
     this.timeUpdate = 0; 
     this.timeLastLogin = 0; 
    } 

    User.prototype = { 
     constructor: User, 
     addEmail: function(email) { 
      this.email = email; 
      return true; 
     } 
    } 
}); 
+1

函数'User()'被定义在内*即“ready”处理程序中,所以它只能从该上下文中调用。它不是全球可用的。你想在哪里调用函数? – Pointy

+1

请注意,User只在被调用的匿名函数内定义,即$(function(){function User(){....}});新的用户()'不起作用 –

+0

哦,yeeess !!!! omg我好蠢! –

回答

2

它必须是scoping问题。

如果你在一个函数中声明了变量,那么它在该函数之外是不可见的。

2

也许你有一个范围问题。我在$(function() { ... })中定义了你的构造函数和原型,它们在这个块之外是不可见的。

$(function() { 

    function User() { 
     this.badgeVervalDatum = null; 
     this.bijNaam = null; 
     this.contactVia = null; 
     this.email = null; 
     this.familieNaam = null; 
     this.gsm = null; 
     this.id = null; 
     this.middleNaam = null; 
     this.postcode = null; 
     this.rkNummer = null; 
     this.sanBekw = null; 
     this.straat = null; 
     this.voorNaam = null; 
     this.volledigNaam = null; 
     this.woonplaats = null; 
     this.timeCreated = 0; 
     this.timeUpdate = 0; 
     this.timeLastLogin = 0; 
    } 

    User.prototype = { 
     constructor: User, 
     addEmail: function(email) { 
      this.email = email; 
      return true; 
     } 
    }  

    var user = new User(); // this is ok 
}); 

var user = new User(); // this will not work 
0

User类不可访问,因为它是在匿名函数中定义的。 您必须使用户在全局范围内可见。 要做到这一点,你可以之后添加函数定义如下一行:

window['User'] = User; 
0

您是通过全球范围内访问用户,但它宣布进入$(function() {}
要获得User变量,只需在您的范围内声明它即可。 Read more about js scopes

例如:

var User; 
$(function() { 
    User = function() {/* ... */}; 
} 
new User();` 

或宣布User$(function(){})范围。

相关问题