Question

I am trying to build a line of code to dynamically change the function name, by doing this I am storing the name of each function in a variable (to grab from an html element, not important). Either way, what I am trying to do is this:

var validateType = $this.data("type");

new Validator.validateType($this.val(), validateLength)

Validator is an object, then ofcourse "validateType" is the name of each subfunction in that object. "validateType" is also the variable.

I am getting this for an error: TypeError: validator.validateType is not a function

I have tried:

 new Validator.window[validateType]($this.val(), validateLength)

But it doesn't work, it says: TypeError: Validator.window is undefined

Was it helpful?

Solution

You need to use the 'bracket' notation. Since you said Validator is an object and not a constructor function, you don't need to use new.

Try this:

Validator[validateType]($this.val(), validateLength)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top