3

In my object init, I am calling the methods with their names. But some time, those methods may not declared or I don't want to call them. in case of that chance, how to prevent my method from call?

here is my calling approach : this[collectionName](); - here the name is parameter I receive. so the method is declared within object.

here is full code :

init: function( collectionName, size ){

            if( (typeof this[collectionName] ) === undefined ) return; //but not works!!!

            this.collectionName = collectionName;
            this.size =  size.toUpperCase() == "SMALL"  ? 20 : size.toUpperCase() == "MEDIUM" ? 35 : lsize.toUpperCase() == "LARGE" ? 50 : "SMALL";

            this[collectionName]();//some time method will not exist. how to check the existence and prevent it from call?
            return this.generateRecords();

        }

I am getting an error when the method is not their then :

New-DataModels.js?bust=1491457640410:69 Uncaught TypeError: this[collectionName] is not a function
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

2 Answers2

2

A variables does exist and is declared, because it wouldn't enter function if it didn't exist because of this:

// it must be === "undefined" (in quotes) actually, not === undefined
if( (typeof this[collectionName] ) === "undefined" ) return; 

However, as mentionted in error, the problem is that

this[collectionName] is not a function

i.e. this[collectionName] does exist, but it is not a function, and thereby you cannot call it.

You can change your function to make sure that this[collectionName] is a function:

init: function( collectionName, size ){
    if (typeof this[collectionName] !== 'function') return;

    this.collectionName = collectionName;
    this.size =  size.toUpperCase() == "SMALL"  ? 20 : size.toUpperCase() == "MEDIUM" ? 35 : lsize.toUpperCase() == "LARGE" ? 50 : "SMALL";

    this[collectionName]();//some time method will not exist. how to check the existence and prevent it from call?
    return this.generateRecords();
}
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
2

You almost got it, just need a small modification in checking the typeof your property. typeof returns a string indicating the type of that object.

if( (typeof this[collectionName] ) === 'undefined' ) return;
// notice how I made 'undefined' into a string

Although I think it would be better if you check if its not a function:

if (typeof this[collectionName] !== 'function') return;
Arnelle Balane
  • 5,437
  • 1
  • 26
  • 32