hasOwnProperty 方法用于检查一个对象是否具有指定属性,它不会沿着原型链查找属性。而 in 操作符用于检查一个对象是否具有指定属性,包括原型链上的属性。
例如,假设有一个对象 obj,它有一个属性 prop,并且 prop 是从原型链继承而来的属性:
function Obj() { this.prop = 'value';}Obj.prototype = { anotherProp: 'anotherValue'};var obj = new Obj();使用 hasOwnProperty 方法和 in 操作符检查属性 prop:
console.log(obj.hasOwnProperty('prop')); // trueconsole.log('prop' in obj); // true使用 hasOwnProperty 方法和 in 操作符检查属性 anotherProp:
console.log(obj.hasOwnProperty('anotherProp')); // falseconsole.log('anotherProp' in obj); // true从上面的例子可以看出,hasOwnProperty 方法只检查对象本身的属性,而 in 操作符在检查时会沿着原型链查找属性。


