search
HomeWeb Front-endJS TutorialJavaScript study notes: Creating objects_javascript skills

JavaScript has built-in objects such as Date, Array, String, etc., which are powerful and easy to use, and everyone loves them. However, when dealing with some complex logic, the built-in objects are very powerless, and developers often need to customize objects. .

According to the definition of JavaScript, an object is a collection of unordered properties, and its properties can contain basic values, objects or functions. That is to say, an object is a set of attributes in no particular order. Each attribute is mapped to a value, which is a set of key-value pairs. The value can be data or an object.

Object is the basic data type of JavaScript. In JavaScript, values ​​other than strings, numbers, true, false, null, and undefined are objects. Therefore, it is very difficult to continue learning JavaScript without understanding the objects. Start learning about objects today.

Overview

Object is a basic data type in JavaScript. In terms of data structure, it is a hash table, which can be regarded as an unordered collection of attributes. Everything else is an object except the original value. These values ​​are accessed through the property name, which can be any string including the null character. To put it simply, an object is a collection of attributes. Each attribute contains a name (key) and a value (value).

To understand what a JavaScript object is, you can think of it this way. In JavaScript, an object is a concrete entity with properties. Take the girl you see. This girl is an object. She has her own attributes. For example, the girl’s height, age, name, etc. Similarly, in JavaScript, properties can also be used to define characteristics of an object.

Create object

Since you want to learn objects, you must first have an object. Then the question arises, how to create an object in JavaScript? Next, let’s take a look at how to create objects in JavaScript.

Many books on JavaScript introduce methods of object creation, mainly including:

Use object literals to create objects (key-value)

Use new to create objects

Use Object.create() to create objects

Use functions to create objects

Create objects using prototypes

Create objects using object literals

Object literal is the simplest form of creating objects. It aims to simplify the process of creating objects containing a large number of properties. The object literal is a mapping table composed of pairs of attribute names (keys) and attribute values ​​(values). Key and value are separated by colons (:), and each pair of key/values ​​is separated by commas (,). The entire mapping Tables are enclosed in curly braces ({}).

The syntax for creating objects through object literals is as follows:

var obj = {
property_1: value_1, // property_# 可能是一个标识符...
2: value_2, // 或者是一个数字
// ...,
"property n": value_n // 或是一个字符串
};

Here obj is the name of the created object, each property_i is an identifier (can be a name, number or string literal), and each value_i is its value, and this value is assigned to property_i. Let’s look at a specific example:

var girl = {
'name': '欣欣',
'age' : 18,
'height': 175,
'weight': 45
}

This example creates an object named girl. The object has four attributes: name, age, height and weight. These four attributes correspond to an attribute value.

When creating an object using an object literal, if you leave its curly braces ({}) empty, you can define an object containing only default properties and methods. Such as:

var obj = {}

When using an object created in this way, you can create object attributes for object obj through the dot (.), that is, obj.key, and assign the object's attribute value. In addition, you can also create object attributes for the object obj through square brackets ([]), that is, obj['key'], and assign the object's attribute value. As an example below:

var girl = {};
girl.name = '欣欣';
girl.age = 18;
girl['height'] = 175;
girl['weight'] = 45;

When printing the girl object in Chrome, the output result is as follows:

console.log(girl);
//Object {name: "欣欣", age: 18, height: 175, weight: 45}

Use new to create objects

You can also create objects by using the new operator followed by the Object constructor (more on the constructor later):

var obj = new Object(); // Same as obj = {}

Although obj is an empty object in the initial state, members can be easily added and used dynamically in JavaScript, so we can continue to add member variables and methods. Such as:

var girl = new Object();
girl['name'] = '欣欣';
girl['age'] = 18;
girl['height'] = 175;
girl['weight'] = 45;

Use Object.create() to create objects

Objects can also be created using the Object.create() method. This method is useful because it allows you to choose the prototype object for the created object without defining a constructor.

The Object.create() method creates an object with the specified prototype and several specified properties.

Object.create(proto, [ propertiesObject ])

The Object.create() method creates an object and accepts two parameters. The first parameter is the prototype object proto of this object; the second is an optional parameter to further describe the properties of the object. . This method is very simple to use:

var obj1 = Object.create({
x: 1,
y: 2
}); //对象obj1继承了属性x和y
var obj2 = Object.create(null); //对象obj2没有原型

如果 proto 参数不是 null 或一个对象值,则抛出一个 TypeError 异常。
有关于Object.create()方法更多的示例可以点击这里进行了解。

使用函数创建对象

在实际使用当中,字面量创建对象虽然很有用,但是它并不能满足我们的所有需求,我们希望能够和其他后台语言一样创建一个类,然后声明类的实例就能够多次使用,而不用每次使用的时候都要重新创建它。

因为JavaScript没有类,一般都是使用函数来定义一个类似其他语言中的类格式,比如:

function Person() {
this.name = "mary"; // 为这个类添加一个成员变量name,并为这个成员变量赋默认值
this.age = 5;
this.sayHello = function () {
console.log(this.name + " : " + this.age);
};
}

定义好类之后,我们就可以像下面这样创建和使用对象:

var person1 = new Person();
person1.name = 'Tom';
person1.age = 20;
person1.sayHello(); // Tom : 20
var person2 = new Person();
person2.name = 'W3cplus';
person2.age = 5;
person2.sayHello(); // W3cplus : 5

Person()函数不是用来被调用的,它是用来被new用的。

通过原型创建对象

这种方法比较前几种方法来说算是最为复杂,最为高级的方法。这里还涉及到封装的一些知识(有关于这些后续学习到了再记录)。这里简单看看如何通过原型创建对象。

首先像函数方法创建对象一样,先定义一个函数:

function Person() {
this.name = "W3cplus";
this.age = 5;
this.walk = function () {
console.log("一个前端网站...");
};
}

然后在外部可以扩允成员:

//添加成员方法
Person.prototype.sayHello = function () {
console.log("hello");
};
//也可以添加成员属性,
Person.prototype.height = 100;

一方面,原型可以扩充原有类的功能(特别是添加有用方法),也可以像下面这样写:

function Person() { }
Person.prototype.name = "W3cplus";
Person.prototype.age = 5;
Person.prototype.walk = function () {
console.log("一个前端网站...");
};
Person.prototype.sayHello = function () {
console.log("hello");
};
Person.prototype.height = 100;

属性访问

对象属性访问一般有两种方法,第一种是使用点(.)表示法,这也是最常用的一种方法,也是很多面向对象语言中通用的语法。第二种方法还可以使用中括号([])表示法来访问对象的属性。在使用中括号语法时,应该将要访问的属性以字符串的形式放在中括号中。如下:

person['name'];
person.name;

从功能上来说,上面两种方法访问对象属性没有任何区别。但中括号语法的主要优点有两个:

可能通过变量访问属性,如下:

var propertyName = 'name';
person[propertyName];

另外一个优点是,如果属性名中包含了会导致语法错误的字符或者属性名使用的是关键字或保留字,可以使用中括号访问属性,如下:

person['first name'];

一般情况之下,除非必须使用亦是来访问对象属性,否则建议使用点(.)的方法来访问对象属性。

总结

对象是JavaScript的基本数据类型,如果要更好的往下学习JavaScript相关的知识,很有必要先把对象整明白。这篇主要介绍了几种创建对象的方法。较为简单的是通过字面量({})和new Object()方法创建,但这两种方法创建的对象复用性较差;使用Object.create()创建对象时不需要定义一个构造函数就允许你在对象中选择其原型对象。除了这几种方法还可以使用函数和原型创建对象,而这两种方法相对来说可复用性强,只是使用较为复杂。

有关JavaScript学习笔记之创建对象的知识小编就给大家介绍到这里,希望对大家有所帮助!

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
JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 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.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

In JavaScript, how to get parameters of a function on a prototype chain in a constructor?In JavaScript, how to get parameters of a function on a prototype chain in a constructor?Apr 04, 2025 pm 09:21 PM

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?Apr 04, 2025 pm 09:18 PM

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool