in运算符、Object.hasOwn()、hasOwnProperty()的区别

in运算符

如果指定的属性在指定的对象或其原型链中,则in 运算符返回true

const car = { make: 'Honda', model: 'Accord', year: 1998 };

console.log('make' in car);
// expected output: true

delete car.make;
if ('make' in car === false) {
  car.make = 'Suzuki';
}

console.log(car.make);
// expected output: "Suzuki"

//原型上的属性一样也可以用in 运算符判断是否存在
console.lg('toString' in car)
// expected output: true

Object.hasOwn()与Object.prototype.hasOwnProperty()

如果对象具有指定的属性作为其自己的 属性,则返回true。如果属性被继承或不存在,则该方法返回 false。

// Object.prototype.hasOwnProperty
const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// expected output: true

console.log(object1.hasOwnProperty('toString'));
// expected output: false

console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false

// Object.hasOwn

console.log(Object.hasOwn(object1, 'property1'));
// expected output: true

console.log(Object.hasOwn(object1, 'toString'));
// expected output: false

console.log(Object.hasOwn(object1, 'undeclaredPropertyValue'));
// expected output: false

你可能感兴趣的:(原型模式,javascript,前端)