0

Hello friends please how can i know if the className name contains a property since i'm using Ajax and i receive my class name as data.className

This is my code :

$.post(action, object, function(data){

    if(data.className.prototype.hasOwnProperty(data.methodName))
        console.log("the property exists")

    return data;
}, 'json');

My object :

{"className":"Quote", "methodName":"deleteQuote"}

This is my class Quote

class Quote{

    deleteQuote(callback){
        console.log("hello world");
    }
}

Thank you

Barmar
  • 669,327
  • 51
  • 454
  • 560
  • Here is a possible solution that does not involve eval. You would put the classes into a map, and use the map to refer to the objects by name. https://yaoganglian.com/2013/07/17/javascript-class-from-string/ – jwatts1980 May 29 '19 at 20:50

1 Answers1

1

The problem with your code is in this part: data.className.prototype. Since data.className == "Quote", this is equivalent to "Quote".prototype, which will get the prototype of the String class and not of the Quote class. So you want to convert the string "Quote" to the class which happens to be named Quote. Accessing variables named by a string is possible in Javascript as can be found here. Unfortunately, this does not work for classes and the only fix seems to be using eval. The resulting code would look like this:

var proto = eval(data.className+".prototype");
if(proto.hasOwnProperty(data.methodName))
    console.log("the property exists")

You should be careful when using eval because it might cause security issues. eval executes any code that is in the string that is passed as an argument. If you know for sure that data.className is a valid identifier, then this is not an issue. If you do not, you should first check that data.className is a valid JavaScript identifier. For how to do this, you can look at the answers to this question.

Max Meijer
  • 1,532
  • 1
  • 14
  • 22