[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn [Back]  [Original]

Object.hasOwn() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Object.hasOwn()

20223

Object.hasOwn() true false

const object1 = {
  prop: "exists",
};

console.log(Object.hasOwn(object1, "prop"));
// Expected output: true

console.log(Object.hasOwn(object1, "toString"));
// Expected output: false

console.log(Object.hasOwn(object1, "undeclaredPropertyValue"));
// Expected output: false

js
Object.hasOwn(obj, prop)

obj

JavaScript

prop

String Symbol

true false

Object.hasOwn() true null undefined false in

Object.prototype.hasOwnProperty() Object.create(null) hasOwnProperty() Object.prototype.hasOwnProperty() Object.hasOwn()

hasOwn

example prop

js
const example = {};
Object.hasOwn(example, "prop"); // false 'prop' 

example.prop = "exists";
Object.hasOwn(example, "prop"); // true 'prop' 

example.prop = null;
Object.hasOwn(example, "prop"); // true null

example.prop = undefined;
Object.hasOwn(example, "prop"); // true undefined

js
const example = {};
example.prop = "exists";

// `hasOwn`  true
Object.hasOwn(example, "prop"); //  true
Object.hasOwn(example, "toString"); //  false
Object.hasOwn(example, "hasOwnProperty"); //  false

// `in`  true
"prop" in example; //  true
"toString" in example; //  true
"hasOwnProperty" in example; //  true

js
const example = { foo: true, bar: true };
for (const name of Object.keys(example)) {
  // 
}

for...in Object.hasOwn()

js
const example = { foo: true, bar: true };
for (const name in example) {
  if (Object.hasOwn(example, name)) {
    // 
  }
}

Array hasOwn()

js
const fruits = ["Apple", "Banana", "Watermelon", "Orange"];
Object.hasOwn(fruits, 3); // true ('Orange')
Object.hasOwn(fruits, 4); // false

hasOwnProperty

hasOwnProperty hasOwn() hasOwnProperty()

js
const foo = {
  hasOwnProperty() {
    return false;
  },
  bar: "The dragons be out of office",
};

if (Object.hasOwn(foo, "bar")) {
  console.log(foo.bar); //true hasOwnProperty()  Object
}

Object.create(null) Object.prototype hasOwnProperty()

js
const foo = Object.create(null);
foo.prop = "exists";
if (Object.hasOwn(foo, "prop")) {
  console.log(foo.prop); //true
}

ECMAScript 2027 LanguageSpecification
# sec-object.hasown


Web Proxy Viewer  |  New URL  |  Original Page