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.

4 Answers 4

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];
Sign up to request clarification or add additional context in comments.

Comments

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)] )

Comments

2

You need to use indexer notation:

if (typeof URIL.Classes[i]["set" + (...)] === "function")

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.