Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ask for a method in javascript prototype

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.

like image 511
Kalamarico Avatar asked May 08 '26 15:05

Kalamarico


2 Answers

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];
like image 143
T.J. Crowder Avatar answered May 11 '26 05:05

T.J. Crowder


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)] )
like image 39
hugomg Avatar answered May 11 '26 05:05

hugomg