Table of Contents
Five common ways to create objects in Javascript:
Related recommendations:" >Related recommendations:
Home Web Front-end JS Tutorial Detailed explanation of five common ways to create objects in Javascript

Detailed explanation of five common ways to create objects in Javascript

Aug 08, 2018 am 09:33 AM
javascript

Five common ways to create objects in Javascript:

There are seven ways to create objects. Here are examples of the five common ways, among which There are two methods that are frequently used, please be sure to master them:

1. Directly create object method

The creation syntax is as follows:

var 对象变量名 = new Object();
对象变量名. property1 = value1;
…;
对象变量名. propertyN = valueN;
对象变量名. methodName1 = function([参数列表]){
    //函数体}
…;
对象变量名. methodNameN = function([参数列表]){
    //函数体}
Copy after login

Create an object first , define and set the values ​​of the properties and functions

Reference examples and calls are as follows:

var student =new Object();student.name="小李";student.age=21;student.dohomework=function(){
    console.log(this.name+"正在做作业");}
console.log(student.name);student.dohomework();
Copy after login

2. Object initializer method

The creation syntax is as follows:

var 对象变量名 = {
    property1 : value1,
    property2 : value2,
    …, 
    propertyN : valueN,
    methodName1 : function([parameter_list]){
        //函数体
    },
    …, 
    methodNameN : function([parameter_list]){
        //函数体
    }
}
Copy after login

Directly assign values ​​​​to the properties of the object and define function functions within the curly brackets

See the reference examples and calls below:

var teacher = {
    name:"Mr Li",
    age:21,
    teach:function(){
        console.log(this.name+"正在授课ing");
    }
}
teacher.teach();
Copy after login

Note : Different attribute values ​​are directly separated by commas, and there is usually no punctuation mark after the last value

3. Constructor method

The creation syntax is as follows:

function 构造函数([参数列表]){ 
    this.属性 = 属性值; 
    …    this.属性N = 属性值N;    this.函数1 = method1; 
    …    this.函数N = methodN; 
}function method1([参数列表]){
    //函数体}
…function methodN([参数列表]){
     //函数体}
Copy after login

or

function  构造函数([参数列表]){ 
    this.属性 = 属性值; 
    …    this.属性N = 属性值N;    this.函数1 = function([参数列表]){
        //函数体
    } ;
    …    this.函数N = function([参数列表]){
        //函数体
    } ;
}
Copy after login

Note: Some values ​​can be set to default values, and some values ​​can be given in the parameter list as needed and assigned directly
Summary:
1. Compared with the above two methods, using the constructor method to create objects can effectively save code;
2. Using the constructor method to create objects, this cannot be omitted, which is the difference between ordinary functions;
3 , use the constructor method to create objects, the method on the left is more preferable, and improves code reuse;

Reference examples and calls are shown below:

function Student(name){
    this.name=name;    this.age=21;    this.play=function(){
        console.log(this.name+"正在玩");
    }
}var student=new Student("仔仔");
student.play();
Copy after login

4.prototype prototype method

The creation syntax is as follows:

function 对象构造器( ){} 
对象构造器.prototype.属性名=属性值;
对象构造器.prototype.函数名 = function([参数列表]){
    //函数体}
Copy after login

After declaring a new function, the function (in JavaScript, the function is also an object) will have a prototype attribute, through which you can Add new properties and methods to objects.

Reference examples and calls are as follows:

function Student(){}
Student.prototype.name="仔仔";
Student.prototype.age=21;
Student.prototype.dohomework=function(){
    console.log(this.name+"正在做作业");
}var student=new Student();
student.dohomework();
Copy after login

5. Mixed constructor/prototype method

The creation syntax is as follows:

function 对象构造器([参数列表]){} 
对象构造器.prototype.函数名 = function([参数列表]){
    //函数体}
Copy after login

The constructor method is convenient for dynamically assigning values ​​​​to properties, but this method also defines the method in the constructor method body, making the code more complicated; while the prototype method is not convenient for dynamically assigning values ​​​​to properties, but the properties and methods defined in this way are Separation is achieved; so learn from each other's strengths and weaknesses - constructors define properties and prototypes define methods.

See reference examples and calls below:

function Student(name){
    this.name=name;    this.age=21;
}
Student.prototype.dohomework=function(){
    console.log(this.name+"正在做作业");
}var student=new Student("仔仔");
student.dohomework();
Copy after login

There are two other methods. Dynamic prototype method and factory mode are not common, so I won’t explain them here. Thank you for watching my work!

#4 ways to create objects in JavaScript

Illustration Seven ways to create objects in javascript

The above is the detailed content of Detailed explanation of five common ways to create objects in Javascript. 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 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles