If the / else condition is inside an object

function Validator(formIsValid) {
    if(this.formIsValid) {
        alert('Form is valid!');
    }
    else {
        alert('Form is invalid...');
    } 
}
Validator.prototype = { // Notice the .prototype here, it 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();

Above was my Val.js. This is how I use in my other File.js file

AddPatient.Firstname = FirstNameValue || Validator.enforceLabelHasText(FirstName);  

I get an error cannot find function enforceLabelHasText in Object function Validator(formIsValid)

+3
source share
5 answers

You cannot put expressions in an object definition. If you want the code to execute after instantiating the object, you should use:

function Validator() {
    if(this.formIsValid) {
        alert('Form is valid!');
    }
    else {
        alert('Form is invalid...');
    } 
}
Validator.prototype = { // Notice the .prototype here, it 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();

This is a fictitious solution; you need to add function arguments Validator()to initialize formIsValidother values ​​as well. I suggest you read the description of MDC on prototypes .

EDIT . If you went with a solution prototype, you need to call val.enforceLabelHasText(FirstName)by making a valglobal variable (either omitting varor using var window.val = new Validator()).

+5

.

if/else , :

var myObj = { a, b, c, d, 
  if (true) {
     alert('WTF!');
  }
};

, , .

+5

Validator is an object literal, and you can only assign properties there, not arbitrary code.

You can assign a function that includes your code in a property.

+2
source

Bind this to a variable at the beginning.

var that = this; 

This saves this change and points to something else. And use firebug!

+1
source

You can insert logic into the object literal using iife . Like this:

const testable = 1
const obj = {
  a: 'value1',
  b: (() => {
    if (testable === 1) {
      return 'testable was 1'
    } else {
      return 'testable was not 1'
    }
   })()
}

console.log(obj)
Run code
+1
source

All Articles