I’m trying to write a simple function which would validate an input but I’m having trouble accessing a parent object function.
I think the problem is that I need a closure but as I’m quite new to js and I’m having difficulty getting my head around closures I thought maybe seeing it in action in my code might help, if it is indeed the problem.
function validate(value, validator){
if(validator == 'login_cred'){
testName(value);
}
var test = {
minLength: function (val, length) {
return val.length >= length;
}
}
function testName(value){
if(!test.minLength(value, 5)){
console.log('more chars please...');
}
}
}
//call
validate("str", 'login_cred');
When I call the function I get test is undefined error.
Is this a case of needing a closure?.. if so how would a closure work best in the above code?
The function testName gets hoisted. Because of this you code actually looks like this.
as you can see test has not been declared yet when it is called, and simple placing testName at the bottom does not change this. Simply change your code to this and it will work.