我在创建构造函数属性时遇到了问题。在firebug控制台中,错误显示为"telekomApp.validation.run is not a function"
。 this.run()
函数应该是TelekomApp
构造函数的属性,我希望它也可以作为telekomApp.validation.run()
工作,但事实并非如此。
请你能解释一下吗?
非常感谢
JS:
(function(global) {
var TelekomApp = function() {
this.validation = function() {
var userNameField = document.getElementById("username-field"),
passwordField = document.getElementById("password-field"),
usernameMsg = document.getElementById("username-msg"),
passwordMsg = document.getElementById("password-msg");
this.run = function(tag) { // this method doesn't work...
var o = this;
};
};
};
// make global
global.TelekomApp = TelekomApp;
// instanciate
var telekomApp = new TelekomApp;
// initialise validation...
telekomApp.validation.run(document.getElementById("login-form"));
}(window));
HTML:
<div id="login">
<p id="message"></p>
<form id="login-form" action="#" method="post">
<fieldset>
<legend>Please login using your username and password</legend>
<ol>
<li>
<label for="username-field">Username <span>*</span></label>
<input type="text" id="username-field" placeholder="Type your username" />
<span id="username-msg"></span>
</li>
<li>
<label for="password-field">Password <span>*</span></label>
<input type="password" id="password-field" placeholder="Type your password" />
<span id="password-msg"></span>
</li>
<li id="button">
<input type="submit" id="login-btn" value="Log In" />
</li>
</ol>
</fieldset>
</form>
</div>
答案 0 :(得分:3)
(function(global) {
var Validation = function() { //constructor for Validation
var userNameField = document.getElementById("username-field"),
passwordField = document.getElementById("password-field"),
usernameMsg = document.getElementById("username-msg"),
passwordMsg = document.getElementById("password-msg");
this.run = function(tag) { // this method doesn't work...
var o = this;
};
};
var TelekomApp = function() {
this.validation = new Validation();
};
// make global
global.TelekomApp = TelekomApp;
// instanciate
var telekomApp = new TelekomApp;
// initialise validation...
telekomApp.validation.run(document.getElementById("login-form"));
}(window));
答案 1 :(得分:1)
telekomApp.validation.run
将在调用telekomApp.validation
时添加到对象中。
this.validation = function() {
将函数添加到对象但不调用它。此外,this.run = function(tag) {
会将run
直接添加到telekomApp
,而不是telekomApp.validation
。
一个小小的改变就是:
var Validation = function() {
...// your code here
}
this.validation = new Validation();