我有一个javascript类,一个对象被传递给它,该对象是匿名的并且发生了变化。我想检查在该对象的属性中是否在该类中有匹配的方法名称。
以下是明确的代码:
var Panel = function(obj) {
for (var prop in obj) {
if (typeOf this[prop] == function) { // ?? please help with this check
this[prop](obj[prop]); // call this method with right argument in this case will be this.maxWidth("400px")
}
}
this.maxWidth = function(max_width) {
document.getElementById(obj["id"]).style.maxWidth = max_width;
}
}
var myObj = {
"maxWidth": "400px"
}
var p = new Panel(myObj);
答案 0 :(得分:1)
以下是更正后的代码,您需要使用typeof
而非typeOf
和function
需要用引号括起来,因为typeof
会返回一个字符串:
var Panel = function(obj) {
for (var prop in obj) {
if (typeof this[prop] == 'function') { // ?? please help with this check
this[prop](obj[prop]); // call this method with right argument in this case will be this.maxWidth("400px")
}
}
this.maxWidth = function(max_width) {
document.getElementById(obj.id).style.maxWidth = max_width;
};
};
var myObj = {
"maxWidth": "400px"
};
var p = new Panel(myObj);