function Validator(formIsValid) {
if(this.formIsValid) {
alert('Form is valid!');
}
else {
alert('Form is invalid...');
}
}
Validator.prototype = { // Notice the .prototype here, it's important!
formIsValid: true,
enforceTextFieldMinLength: function(field, minLength) {
if (!field.value || field.value.length < minLength) {
this.formIsValid = false;
}
},
enforceLabelHasText: function(label) {
if (!label.text) {
this.formIsValid = false;
}
}
}
//var val = new Validator();
Run Code Online (Sandbox Code Playgroud)
以上是我的Val.js. 这就是我在otherFile.js中使用的方式
AddPatient.Firstname = FirstNameValue || Validator.enforceLabelHasText(FirstName);
Run Code Online (Sandbox Code Playgroud)
我收到一个错误说 cannot find function enforceLabelHasText in Object function Validator(formIsValid)
这不是有效的语法.
您已if/else在对象定义中转储条件,如下所示:
var myObj = { a, b, c, d,
if (true) {
alert('WTF!');
}
};
Run Code Online (Sandbox Code Playgroud)
像这样的程序代码必须在函数内部.
您不能将表达式放在对象定义中.如果要在创建对象实例后执行代码,则应使用:
function Validator() {
if(this.formIsValid) {
alert('Form is valid!');
}
else {
alert('Form is invalid...');
}
}
Validator.prototype = { // Notice the .prototype here, it's important!
formIsValid: true,
enforceTextFieldMinLength: function(field, minLength) {
if (!field.value || field.value.length < minLength) {
this.formIsValid = false;
}
},
enforceLabelHasText: function(label) {
if (!label.text) {
this.formIsValid = false;
}
}
}
var a = new Validator();
Run Code Online (Sandbox Code Playgroud)
这是一个虚拟解决方案; 您将要为Validator()函数添加参数,初始化formIsValid和其他值.我建议你应该阅读MDC对原型的描述.
编辑:如果您使用原型解决方案,则需要val.enforceLabelHasText(FirstName)在创建val全局变量之后调用(通过省略var或使用var window.val = new Validator()).