search
HomeWeb Front-endFront-end Q&ACommon methods of javascript objects

JavaScript is a popular programming language used to create interactive web pages and dynamic web applications. The most important part of it is objects, which allow programmers to create, store and manipulate data. In this article, we will take a deep dive into common methods of JavaScript objects.

  1. Creating Objects

In JavaScript, we can create objects in two ways. The first is to use object literals. It is a simple, intuitive syntax for creating objects containing key-value pairs. For example:

let person = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

The second method is to use the constructor. A constructor is a special function used to create objects. It uses the keyword new and the function name to create a new instance. For example:

function Person(firstName, lastName) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
    this.sayHello = function() { 
        console.log("Hello, my name is " + this.firstName + " " + 
        this.lastName); 
    } 
}

let john = new Person("John", "Doe"); 
john.sayHello(); // 输出 "Hello, my name is John Doe"
  1. Accessing and modifying object properties

In JavaScript, we can use the dot operator or square bracket operator to access and modify object properties. For example:

let person = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

console.log(person.firstName); // 输出 "John"
person.age = 40;
console.log(person.age); // 输出 40 

person["lastName"] = "Smith";
console.log(person.lastName); // 输出 "Smith"
  1. Traversing object properties

There are two common methods of traversing object properties in JavaScript: for-in loop and Object.keys() method.

Use a for-in loop to traverse all enumerable properties of an object. For example:

let person = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

for (let prop in person) { 
    console.log(prop + ": " + person[prop]); 
} 

/*
输出:
firstName: John
lastName: Doe
age: 30
*/

Use the Object.keys() method to return an array containing the names of all enumerable properties of the object. For example:

let person = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

let props = Object.keys(person);
console.log(props); // 输出 ["firstName", "lastName", "age"]
  1. Delete object properties

In JavaScript, we can use the delete operator to delete the properties of an object. For example:

let person = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

delete person.age; // 删除age属性
console.log(person); // 输出 {firstName: "John", lastName: "Doe"}
  1. Determine whether the object property exists

In JavaScript, we can use the in operator or the hasOwnProperty() method to determine whether the object contains a certain property. For example:

let person = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

console.log("firstName" in person); // 输出 true
console.log("gender" in person); // 输出 false

console.log(person.hasOwnProperty("firstName")); // 输出 true
console.log(person.hasOwnProperty("gender")); // 输出 false
  1. Renaming an object property

In JavaScript, we can do this by creating a new property and setting its value to the value of the old property, and then using delete Operator renames object properties by removing old properties. For example:

let person = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

person.fullName = person.firstName + " " + person.lastName;
delete person.firstName;
delete person.lastName;

console.log(person); // 输出 {fullName: "John Doe", age: 30}
  1. Clone Object

In JavaScript, we can use the Object.assign() method or the spread operator (...) to shallow clone an object. This means that the original object and the copy object share properties of the same reference type. For example:

let person = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

let clone = Object.assign({}, person);
console.log(clone); // 输出 {firstName: "John", lastName: "Doe", age: 30}

let { ...copy } = person;
console.log(copy); // 输出 {firstName: "John", lastName: "Doe", age: 30}

To create a deep clone, that is, create a new reference value type property in the copy object, we need to use recursion or library functions.

  1. Freezing Objects

In JavaScript, we can use the Object.freeze() method to freeze an object, thereby prohibiting modification of its properties and methods. For example:

let person = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

Object.freeze(person);

person.age = 40;
console.log(person.age); // 输出 30

person.fullName = person.firstName + " " + person.lastName;
console.log(person.fullName); // 输出 undefined
  1. Object comparison

In JavaScript, when we compare two objects using == and === operators, they will only return true, If and only if two objects refer to the same object. If we need to compare properties and methods of two objects, we need to manually compare each of their properties and methods. For example:

let person1 = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

let person2 = { 
    firstName: "John", 
    lastName: "Doe", 
    age: 30 
};

let isEqual = true;

for (let prop in person1) { 
    if (person1[prop] !== person2[prop]) { 
        isEqual = false; 
        break; 
    } 
}

console.log(isEqual); // 输出 true

To sum up, objects are a basic concept and building block in JavaScript programming. Understanding the common methods of JavaScript objects allows programmers to create, store, and manipulate data more efficiently, thereby building better web applications.

The above is the detailed content of Common methods of javascript objects. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

CSS ID and Class: common mistakesCSS ID and Class: common mistakesMay 13, 2025 am 12:11 AM

IDsshouldbeusedforJavaScripthooks,whileclassesarebetterforstyling.1)Useclassesforstylingtoallowforeasierreuseandavoidspecificityissues.2)UseIDsforJavaScripthookstouniquelyidentifyelements.3)Avoiddeepnestingtokeepselectorssimpleandimproveperformance.4

What is thedifference between class and id selector?What is thedifference between class and id selector?May 12, 2025 am 12:13 AM

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

CSS IDs vs Classes: The real differencesCSS IDs vs Classes: The real differencesMay 12, 2025 am 12:10 AM

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

CSS: What if I use just classes?CSS: What if I use just classes?May 12, 2025 am 12:09 AM

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and Class Selectors in CSS: A Beginner's GuideID and Class Selectors in CSS: A Beginner's GuideMay 12, 2025 am 12:06 AM

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.

See all articles

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor