2014-10-22 64 views
0

我正在一個項目中,我從另一個對象/函數引用一個變量。然而,我總是返回false。我不確定我是否正確調用它。總是返回false | Javascript |對象

下面是驗證功能:

app.validation = function(){ 
    'use strict'; 
    var validCheck = true; 

    if((app.process.user.length < 3) || (app.process.user.length > 50)){ 
     validCheck = false; 
     window.alert("The username is not acceptable. Example: username"); 
    }; 
    if((app.process.name.length < 3) || (app.process.name.length > 50) || (!app.process.name.indexOf(" ") === -1)){ 
     validCheck = false; 
     window.alert("The name is not acceptable. Example: John Smith"); 
    }; 
    if((app.process.email.length < 3) || (app.process.email.length > 100) || (!app.process.email.indexOf("@") === -1)){ 
     validCheck = false; 
     window.alert("The email is not acceptable. Example: [email protected]"); 
    }; 
    if((app.process.passlength < 6) || (app.process.pass.length > 20)){ 
     validCheck = false; 
     window.alert("The password is not acceptable. Example: password"); 
    }; 
    if((app.process.age.length < 1) || (app.process.age.length > 2)){ 
     validCheck = false; 
     window.alert("The age is not acceptable. Example: 22"); 
    }; 
    return validCheck; 
}; 

這是對變量的存儲:

app.process = function(){ 
    'use strict'; 
    var user = document.getElementById("user").value; 
    var name = document.getElementById("name").value; 
    var email = document.getElementById("email").value; 
    var pass = document.getElementById("pass").value; 
    var age = document.getElementById("age").value; 

    var test = app.validation(); 
    console.log(test); 
    if(!test){ 
     window.alert("Try Again."); 
    }else{ 
     app.reset(); 
     app.members[app.members.length] = new app.Member(user, name, email, pass, age); 
     app.printMembers(); 
    }; 
}; 

還有更多這個代碼但是是到大在這裏發表。這是導致問題的兩個功能。

回答

1

您不能訪問app.process變量,因爲它們對函數是私有的。您需要以某種方式將這些值傳遞給app.validation以驗證它們。

我會做的方式是

var data = { 
    user: document.getElementById("user").value, 
    name: document.getElementById("name").value, 
    email: document.getElementById("email").value, 
    pass: document.getElementById("pass").value, 
    age: document.getElementById("age").value 
}; 

var test = app.validation(data); 

而且在驗證

app.validation = function(data) { ... 

而且每次更換爲app.process.fielddata.field

+0

數據是在流程方法中還是在全局範圍內定義? – hudsond7 2014-10-22 00:54:22

+0

其中,總是在:)全局變量是來自地獄。 – 2014-10-22 01:46:37

+0

謝謝你的幫助。 – hudsond7 2014-10-22 11:46:04