在javascript原型中请求一个方法

ask for a method in javascript prototype

本文关键字:一个 方法 javascript 原型 请求      更新时间:2023-09-26

我有一个问题,我在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;
}

当我序列化json字符串到这种类型的对象时,我想问是否存在setEntity方法,我有这个json:

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

当我读"实体"我想知道是否存在一个方法"setEntity"在FactVal类,我认为我必须这样做:'i'的值是"FactVal"和'j'的值是"实体"。

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

不工作,我该怎么做?

谢谢。

你很接近了,你想要[],你需要查看构造函数的prototype属性,而不是构造函数本身:

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

(我也用j.charAt(0)代替了你的j[0],并不是所有的JavaScript引擎都支持这样的字符串索引。)

或更好:

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

这是有效的,因为您可以通过熟悉的点符号和文字来访问对象的属性:

x = obj.foo;

…或者通过带括号的字符串符号:

x = obj["foo"];
// or
s = "foo";
x = obj[s];
// or
p1 = "f";
p2 = "o";
x = obj[p1 + p2 + p2];

代替

FactVal.setEntity

你必须查看原型,就像你最初设置属性时所做的那样:

Factval.prototype.setEntity

同样,您需要使用括号符号而不是圆括号(就像您使用[i]一样):

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

您需要使用索引器表示法:

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

你的问题是这样的:

使用方法将JSON字符串转换为对象

然而,那一行:

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

应替换为:

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

注意:j.substr(1)等价于j.substring(1,j.length)