2

i have one question, i have this class in javascript:

//FactVal
UTIL.Classes.FactVal = function(entity, attribute, value) {
    this.entity = entity;
    this.attribute = attribute;
    this.value = value;
}

UTIL.Classes.FactVal.prototype.setEntity = function(entity) {
    this.entity = entity;
}

When im serializing a json string to an object of this type, i want to ask if exists the setEntity method, i have this json:

"FactVal": {
              "entity": {
               "string": "blabla"
              }
}

When i read "entity" i want to know if exists a method "setEntity" in the FactVal class, i think i have to do this: the value of 'i' is "FactVal" and the value of 'j' is "entity".

if(UTIL.Classes[i].("set" + j[0].toUpperCase() + j.substring(1,j.length)))

and dont work, how can i do it?

Thanks.

hugomg
  • 68,213
  • 24
  • 160
  • 246
Kalamarico
  • 5,466
  • 22
  • 53
  • 70

4 Answers4

3

You're close, you want [] and you need to look at the prototype property of the constructor function, not the constructor function itself:

if(UTIL.Classes[i].prototype["set" + j.charAt(0).toUpperCase() + j.substring(1,j.length)])

(I also replaced your j[0] with j.charAt(0), not all JavaScript engines in the wild support indexing into strings like that yet.)

Or better:

if(typeof UTIL.Classes[i].prototype["set" + j.charAt(0).toUpperCase() + j.substring(1,j.length)] === "function")

That works because you can access the property of an object either via the familiar dotted notation with a literal:

x = obj.foo;

...or via bracketed notation with a string:

x = obj["foo"];
// or
s = "foo";
x = obj[s];
// or
p1 = "f";
p2 = "o";
x = obj[p1 + p2 + p2];
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Instead of

FactVal.setEntity

You have to look at the prototype, just like you did when setting the property originally:

Factval.prototype.setEntity

also, you need to use bracket notation istead of parenthesis (like you did with the [i]):

if( UTIL.Classes[i].prototype["set" + j[0].toUpperCase() + j.substring(1,j.length)] )
hugomg
  • 68,213
  • 24
  • 160
  • 246
2

You need to use indexer notation:

if (typeof URIL.Classes[i]["set" + (...)] === "function")
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

Your question looks like this :

Turning JSON strings into objects with methods

However, that line :

if(UTIL.Classes[i].("set" + j[0].toUpperCase() + j.substring(1,j.length)))

Should be replaced with :

if(typeof UTIL.Classes[i]["set" + j[0].toUpperCase() + j.substr(1)] === "function")

NOTE : j.substr(1) is equivalent to j.substring(1,j.length)

Community
  • 1
  • 1
fflorent
  • 1,596
  • 9
  • 11