如何检查匿名对象是否有方法?

2022-08-30 01:55:20

如何检查是否创建如下匿名对象:

var myObj = { 
    prop1: 'no',
    prop2: function () { return false; }
}

确实定义了 prop2 吗?

prop2将始终被定义为函数,但对于某些对象,它不是必需的,也不会被定义。

我尝试了这里建议的内容:如何确定本机JavaScript对象是否具有属性/方法?但我认为它不适用于匿名对象 。


答案 1

typeof myObj.prop2 === 'function';将让您知道该函数是否已定义。

if(typeof myObj.prop2 === 'function') {
    alert("It's a function");
} else if (typeof myObj.prop2 === 'undefined') {
    alert("It's undefined");
} else {
    alert("It's neither undefined nor a function. It's a " + typeof myObj.prop2);
}

答案 2

你想要:hasOwnProperty()

var myObj1 = { 
	prop1: 'no',
	prop2: function () { return false; }
}
var myObj2 = { 
	prop1: 'no'
}

console.log(myObj1.hasOwnProperty('prop2')); // returns true
console.log(myObj2.hasOwnProperty('prop2')); // returns false
	

参考资料:MozillaMicrosoft、phrogz.net