我通常使用
typeof运算符:
if (typeof obj.foo !== 'undefined') { // your pre here}"undefined"如果该属性不存在或其值是,它将返回
undefined。
if (obj.hasOwnProperty('foo')) { // your pre here}和
in运算符:
if ('foo' in obj) { // your pre here}后两者之间的区别在于,该
hasOwnProperty方法将检查属性是否 物理 存在于对象上(该属性未继承)。
该
in运营商将检查所有属性在原型链,如到达了:
var obj = { foo: 'bar'};obj.hasOwnProperty('foo'); // trueobj.hasOwnProperty('toString'); // false'toString' in obj; // true如您所见,在检查方法时会
hasOwnProperty返回
false,而
in操作员会返回,该方法在原型链中定义,因为它继承了form。
true``toString``obj``Object.prototype



