Home Web Front-end JS Tutorial A Guide to Master JavaScript-Objects

A Guide to Master JavaScript-Objects

Jul 18, 2024 pm 04:46 PM

A Guide to Master JavaScript-Objects

Objects are a fundamental part of JavaScript, serving as the backbone for storing and managing data. An object is a collection of properties, and each property is an association between a key (or name) and a value. Understanding how to create, manipulate, and utilize objects is crucial for any JavaScript developer. In this article, we’ll explore the various object functions in JavaScript, providing detailed explanations, examples, and comments to help you master them.

Introduction to Objects in JavaScript

In JavaScript, objects are used to store collections of data and more complex entities. They are created using object literals or the Object constructor.

// Using object literals
let person = {
    name: "John",
    age: 30,
    city: "New York"
};

// Using the Object constructor
let person = new Object();
person.name = "John";
person.age = 30;
person.city = "New York";
Copy after login

Object Properties

  • Object.prototype: Every JavaScript object inherits properties and methods from its prototype.
let obj = {};
console.log(obj.__proto__ === Object.prototype); // Output: true
Copy after login

Object Methods

1. Object.assign()

Copies the values of all enumerable own properties from one or more source objects to a target object. It returns the target object.

let target = {a: 1};
let source = {b: 2, c: 3};
Object.assign(target, source);
console.log(target); // Output: {a: 1, b: 2, c: 3}
Copy after login

2. Object.create()

Creates a new object with the specified prototype object and properties.

let person = {
    isHuman: false,
    printIntroduction: function() {
        console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
    }
};

let me = Object.create(person);
me.name = "Matthew";
me.isHuman = true;
me.printIntroduction(); // Output: My name is Matthew. Am I human? true
Copy after login

3. Object.defineProperties()

Defines new or modifies existing properties directly on an object, returning the object.

let obj = {};
Object.defineProperties(obj, {
    property1: {
        value: true,
        writable: true
    },
    property2: {
        value: "Hello",
        writable: false
    }
});
console.log(obj); // Output: { property1: true, property2: 'Hello' }
Copy after login

4. Object.defineProperty()

Defines a new property directly on an object or modifies an existing property and returns the object.

let obj = {};
Object.defineProperty(obj, 'property1', {
    value: 42,
    writable: false
});
console.log(obj.property1); // Output: 42
obj.property1 = 77; // No error thrown, but the property is not writable
console.log(obj.property1); // Output: 42
Copy after login

5. Object.entries()

Returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

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

6. Object.freeze()

Freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, and prevents the values of existing properties from being changed.

let obj = {prop: 42};
Object.freeze(obj);
obj.prop = 33; // Fails silently in non-strict mode
console.log(obj.prop); // Output: 42
Copy after login

7. Object.fromEntries()

Transforms a list of key-value pairs into an object.

let entries = new Map([['foo', 'bar'], ['baz', 42]]);
let obj = Object.fromEntries(entries);
console.log(obj); // Output: { foo: 'bar', baz: 42 }
Copy after login

8. Object.getOwnPropertyDescriptor()

Returns a property descriptor for an own property (that is, one directly present on an object and not in the object's prototype chain) of a given object.

let obj = {property1: 42};
let descriptor = Object.getOwnPropertyDescriptor(obj, 'property1');
console.log(descriptor);
// Output: { value: 42, writable: true, enumerable: true, configurable: true }
Copy after login

9. Object.getOwnPropertyDescriptors()

Returns an object containing all own property descriptors of an object.

let obj = {property1: 42};
let descriptors = Object.getOwnPropertyDescriptors(obj);
console.log(descriptors);
/* Output:
{
  property1: {
    value: 42,
    writable: true,
    enumerable: true,
    configurable: true
  }
}
*/
Copy after login

10. Object.getOwnPropertyNames()

Returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly upon a given object.

let obj = {a: 1, b: 2, c: 3};
let props = Object.getOwnPropertyNames(obj);
console.log(props); // Output: ['a', 'b', 'c']
Copy after login

11. Object.getOwnPropertySymbols()

Returns an array of all symbol properties found directly upon a given object.

let obj = {};
let sym = Symbol('foo');
obj[sym] = 'bar';
let symbols = Object.getOwnPropertySymbols(obj);
console.log(symbols); // Output: [Symbol(foo)]
Copy after login

12. Object.getPrototypeOf()

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

let proto = {};
let obj = Object.create(proto);
console.log(Object.getPrototypeOf(obj) === proto); // Output: true
Copy after login

13. Object.is()

Determines whether two values are the same value.

console.log(Object.is('foo', 'foo')); // Output: true
console.log(Object.is({}, {})); // Output: false
Copy after login

14. Object.isExtensible()

Determines if extending of an object is allowed.

let obj = {};
console.log(Object.isExtensible(obj)); // Output: true
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj)); // Output: false
Copy after login

15. Object.isFrozen()

Determines if an object is frozen.

let obj = {};
console.log(Object.isFrozen(obj)); // Output: false
Object.freeze(obj);
console.log(Object.isFrozen(obj)); // Output: true
Copy after login

16. Object.isSealed()

Determines if an object is sealed.

let obj = {};
console.log(Object.isSealed(obj)); // Output: false
Object.seal(obj);
console.log(Object.isSealed(obj)); // Output: true
Copy after login

17. Object.keys()

Returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

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

18. Object.preventExtensions()

Prevents any extensions of an object.

let obj = {};
Object.preventExtensions(obj);
obj.newProp = 'test'; // Throws an error in strict mode
console.log(obj.newProp); // Output: undefined
Copy after login

19. Object.seal()

Seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable.

let obj = {property1: 42};
Object.seal(obj);
obj.property1 = 33;
delete obj.property1; // Throws an error in strict mode
console.log(obj.property1); // Output: 33
Copy after login

20. Object.setPrototypeOf()

Sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null.

let proto = {};
let obj = {};
Object.setPrototypeOf(obj, proto);
console.log(Object.getPrototypeOf(obj) === proto); // Output: true
Copy after login

21. Object.values()

Returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop.

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

Practical Examples

Example 1: Cloning an Object

Using Object.assign() to clone an object.

let obj = {a: 1, b: 2};
let clone = Object.assign({}, obj);
console.log(clone); // Output: {a: 1, b: 2}
Copy after login

Example 2: Merging Objects

Using Object.assign() to merge objects.

let obj1 = {a: 1, b: 2};
let obj2 = {b: 3, c: 4};
let merged = Object.assign({},

 obj1, obj2);
console.log(merged); // Output: {a: 1, b: 3, c: 4}
Copy after login

Example 3: Creating an Object with a Specified Prototype

Using Object.create() to create an object with a specified prototype.

let proto = {greet: function() { console.log("Hello!"); }};
let obj = Object.create(proto);
obj.greet(); // Output: Hello!
Copy after login

Example 4: Defining Immutable Properties

Using Object.defineProperty() to define immutable properties.

let obj = {};
Object.defineProperty(obj, 'immutableProp', {
    value: 42,
    writable: false
});
console.log(obj.immutableProp); // Output: 42
obj.immutableProp = 77; // Throws an error in strict mode
console.log(obj.immutableProp); // Output: 42
Copy after login

Example 5: Converting an Object to an Array

Using Object.entries() to convert an object to an array of key-value pairs.

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

Conclusion

Objects are a core component of JavaScript, offering a flexible way to manage and manipulate data. By mastering object functions, you can perform complex operations with ease and write more efficient and maintainable code. This comprehensive guide has covered the most important object functions in JavaScript, complete with detailed examples and explanations. Practice using these functions and experiment with different use cases to deepen your understanding and enhance your coding skills.

The above is the detailed content of A Guide to Master JavaScript-Objects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles