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";
Object Properties
- Object.prototype: Every JavaScript object inherits properties and methods from its prototype.
let obj = {}; console.log(obj.__proto__ === Object.prototype); // Output: true
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}
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
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' }
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
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]]
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
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 }
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 }
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 } } */
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']
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)]
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
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
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
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
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
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']
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
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
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
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]
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}
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}
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!
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
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]]
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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
