2013-03-13 73 views
0

我无法创建构造函数属性。在萤火虫控制台中,错误表示"telekomApp.validation.run is not a function"this.run()函数应该是TelekomApp构造函数的属性,我期望它也可以作为telekomApp.validation.run()工作,但事实并非如此。Javascript构造函数属性不起作用时调用

请你对此有所了解吗?

非常感谢

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> 

回答

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)); 
+0

谢谢@彼得里昂,它现在的作品。 – Shaoz 2013-03-13 17:47:42

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(); 
+0

感谢您的努力@zeroflagL – Shaoz 2013-03-13 17:48:16

+0

不客气 – zeroflagL 2013-03-13 17:52:51