运算in符和hasOwnProperty函数是检查对象是否包含特定键的常用方法。
const person = {
name: 'Foo',
};
'name' in person; // true
person.hasOwnProperty('name'); // true
差异
-
对于继承的属性,
in将返回true.hasOwnProperty顾名思义,会检查一个属性是否为自己所有,而忽略继承的属性。让我们重用前面示例中的 person 对象。
constructor由于它是一个 JavaScript 对象,具有诸如,之类的内置属性__proto__,因此以下检查返回 true:'constructor' in person; // true '__proto__' in person; // true 'toString' in person; // true当检查这些属性和方法时
hasOwnProperty返回:falseperson.hasOwnProperty('constructor'); // false person.hasOwnProperty('__proto__'); // false person.hasOwnProperty('toString'); // false -
对于类的
get和方法,也返回。set``hasOwnProperty``false例如,我们有一个表示三角形的简单类:
class Triangle { get vertices() { return 3; } } // Create new instance const triangle = new Triangle();尽管这
vertices是以下财产的事实triangle:triangle.vertices; // 3 'vertices' in triangle; // truehasOwnProperty仍然忽略它:triangle.hasOwnProperty('vertices'); // false
好的做法
要检查属性是否存在,请使用hasOwnProperty. 用于in检查方法是否存在。