首頁  >  文章  >  web前端  >  了解 JavaScript 中的關鍵物件方法

了解 JavaScript 中的關鍵物件方法

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-18 12:53:04582瀏覽

Understanding Key Object Methods in JavaScript

JavaScript’s Object comes packed with a number of useful methods that help developers manipulate objects with ease. Let’s walk through some of the most important ones, with brief explanations and examples

  1. Object.create()
  2. Object.assign()
  3. Object.keys()
  4. Object.values()
  5. Object.entries()
  6. Object.freeze()
  7. Object.seal()
  8. Object.preventExtensions()
  9. Object.getPrototypeOf()
  10. Object.setPrototypeOf()
  11. Object.defineProperty()
  12. Object.defineProperties()
  13. Object.getOwnPropertyDescriptor()
  14. Object.getOwnPropertyDescriptors()
  15. Object.getOwnPropertyNames()
  16. Object.is()
  17. Object.isFrozen()
  18. Object.isSealed()
  19. Object.isExtensible()
  20. Object.fromEntries()
  21. Object.hasOwnProperty()
  22. Object.hasOwn()
  23. Object.groupBy() (proposed feature, may not be fully available)

Object.create()
Object.create() is a method in JavaScript used to create a new object with a specified prototype object and optional properties. It allows for more fine-grained control over an object's prototype and properties compared to using object literals or constructors.

const personPrototype = {
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const john = Object.create(personPrototype);
john.name = "John";
john.greet();  // Output: Hello, my name is John

Object.assign()
Object.assign() is a built-in JavaScript method used to copy the values of all enumerable own properties from one or more source objects to a target object. It performs a shallow copy and returns the modified target object.

const target = { a: 1 };
const source = { b: 2, c: 3 };
const result = Object.assign(target, source);
console.log(result);  // Output: { a: 1, b: 2, c: 3 }
console.log(target);  // Output: { a: 1, b: 2, c: 3 } (target is also modified)

Object.keys()
Returns an array of the object’s own enumerable property names (keys)

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));  // Output: ['a', 'b', 'c']

Object.values()
Returns an array of the object’s own enumerable property values

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj));  // Output: [1, 2, 3]

Object.entries()
Returns an array of the object’s own enumerable property [key, value] pairs

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj));  // Output: [['a', 1], ['b', 2], ['c', 3]]

Object.freeze()
Freezes the object, preventing new properties from being added or existing properties from being changed or deleted

const obj = { a: 1 };
Object.freeze(obj);
obj.a = 2;  // No effect, because the object is frozen
console.log(obj.a);  // Output: 1

Object.seal()
Seals the object, preventing new properties from being added, but allows existing properties to be modified.

const obj = { a: 1 };
Object.seal(obj);
obj.a = 2;  // Allowed
delete obj.a;  // Not allowed
console.log(obj.a);  // Output: 2

Object.preventExtensions()
Prevents any new properties from being added to the object, but allows modification and deletion of existing properties

const obj = { a: 1 };
Object.preventExtensions(obj);
obj.b = 2;  // Not allowed
console.log(obj.b);  // Output: undefined

Object.getPrototypeOf()
Returns the prototype (i.e., the internal [[Prototype]]) of the specified object

const obj = {};
const proto = Object.getPrototypeOf(obj);
console.log(proto);  // Output: {} (the default Object prototype)

Object.setPrototypeOf()
Sets the prototype of a specified object.

const proto = { greet() { console.log('Hello!'); } };
const obj = {};
Object.setPrototypeOf(obj, proto);
obj.greet();  // Output: 'Hello!'

Object.defineProperty()
Defines a new property on an object or modifies an existing one, with additional options for property descriptors (e.g., writable, configurable).

const obj = {};
Object.defineProperty(obj, 'a', {
  value: 42,
  writable: false,  // Cannot modify the value
});
obj.a = 100;  // No effect because writable is false
console.log(obj.a);  // Output: 42

Object.defineProperties()
Defines multiple properties on an object with property descriptors.

const obj = {};
Object.defineProperties(obj, {
  a: { value: 42, writable: false },
  b: { value: 100, writable: true }
});
console.log(obj.a);  // Output: 42
console.log(obj.b);  // Output: 100

Object.getOwnPropertyDescriptor()
Returns the descriptor for a property of an object.

const obj = { a: 1 };
const descriptor = Object.getOwnPropertyDescriptor(obj, 'a');
console.log(descriptor);  
// Output: { value: 1, writable: true, enumerable: true, configurable: true }

Object.getOwnPropertyDescriptors()
Returns an object containing all property descriptors for an object’s own properties

const obj = { a: 1 };
const descriptors = Object.getOwnPropertyDescriptors(obj);
console.log(descriptors);
// Output: { a: { value: 1, writable: true, enumerable: true, configurable: true } }

Object.getOwnPropertyNames()
Returns an array of all properties (including non-enumerable ones) found directly on an object.

const obj = { a: 1 };
Object.defineProperty(obj, 'b', { value: 2, enumerable: false });
console.log(Object.getOwnPropertyNames(obj));  // Output: ['a', 'b']

Object.is()
Compares if two values are the same (like === but handles special cases like NaN)

console.log(Object.is(NaN, NaN));  // Output: true
console.log(Object.is(+0, -0));    // Output: false

Object.isFrozen()
Checks if an object is frozen

const obj = Object.freeze({ a: 1 });
console.log(Object.isFrozen(obj));  // Output: true

Object.isSealed()
Checks if an object is sealed.

const obj = Object.seal({ a: 1 });
console.log(Object.isSealed(obj));  // Output: true

Object.isExtensible()
Checks if new properties can be added to an object.

const obj = { a: 1 };
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj));  // Output: false

Object.fromEntries()
Converts an array of key-value pairs into an object

const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);
console.log(obj);  // Output: { a: 1, b: 2 }

Object.hasOwnProperty()
Checks if an object has the specified property as its own (not inherited)

const obj = { a: 1 };
console.log(obj.hasOwnProperty('a'));  // Output: true

Object.hasOwn()
Object.hasOwn() is a newer method introduced in ES2022 as an alternative to Object.hasOwnProperty(). It checks whether an object has a direct (own) property with a specified key, without looking up the prototype chain.

const obj = {
  name: 'Alice',
  age: 25
};

console.log(Object.hasOwn(obj, 'name'));  // true
console.log(Object.hasOwn(obj, 'gender'));  // false

Object.groupBy
Object.groupBy is a relatively new feature proposed for JavaScript in ECMAScript 2024 that allows you to group objects based on a common criterion. It is not yet widely available across all environments, so it may not work in many browsers or JavaScript engines until fully implemented.

const array = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 30 },
];

// Group objects by age
const groupedByAge = Object.groupBy(array, item => item.age);

console.log(groupedByAge);

/*
Expected Output:
{
  25: [
    { name: 'Alice', age: 25 },
    { name: 'Charlie', age: 25 }
  ],
  30: [
    { name: 'Bob', age: 30 },
    { name: 'David', age: 30 }
  ]
}
*/

以上是了解 JavaScript 中的關鍵物件方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn