search
HomeWeb Front-endJS TutorialHelp you get JavaScript objects

This article brings you relevant knowledge about javascript, which mainly introduces related issues about objects, including knowledge points about constructors and various built-in objects. I hope it will be useful to everyone. help.

Help you get JavaScript objects

Related recommendations: javascript tutorial

1. Constructor

Why use constructor

What is a constructor: It is another way for JavaScript to create objects.

Comparison with creating objects using literal methods: Constructors can create some objects with the same characteristics.

Example: Create apple, banana, and orange objects through the fruit constructor. Its characteristic is that these objects are all created based on the same template, and each object has its own characteristics.

Characteristics of creating objects using literals

  • Advantages: Simple and flexible.

  • Disadvantages: When you need to create a set of objects with the same characteristics, you cannot specify through code which members these objects should have.

  • The way to implement templates in object-oriented programming languages: use classes to create templates, and implement different objects (instances of classes) based on the templates.

  • Ways to implement templates in JavaScript 1: Through factory functions, objects are created internally through literals "{ }". The disadvantage is that the type of the object cannot be distinguished.

  • How JavaScript implements templates 2: Create objects through constructors.

JavaScript's built-in constructor

Before learning how to customize the constructor, let's first take a look at how to use the JavaScript's built-in constructor.

  • Common built-in constructors: Object, String, Number and other constructors.
  • How the constructor creates an object: new constructor name ().
  • What is instantiation and instance: People are accustomed to calling the process of creating an object using the new keyword as instantiation, and the object obtained after instantiation is called an instance of the constructor.

Help you get JavaScript objects

  • The "object.constructor" property points to the constructor of the object.
  • When output through console.log(), [native code] indicates that the code of the function is built-in.

Custom constructor

Thinking: How to customize the constructor?

  • It is recommended to use the Pascal naming rule when naming constructors, that is, capitalize the first letter of all words.
  • Inside the constructor, use this to represent the object just created.

Help you get JavaScript objects

Note

When learning JavaScript, beginners are often confused by some similar nouns, such as functions , methods, constructors, constructors, constructors, etc.

In fact, they can all be collectively called functions, but they have different names in different usage scenarios. By convention, functions defined in an object are called methods of the object.

As for the constructor, some people are accustomed to calling it a constructor or a constructor. We only need to understand that these names refer to the same thing.

The new class keyword in ES6

  • The reason why it was not available before ES6: To simplify the difficulty.

  • Reason for adding: With the development of Web front-end technology, some people who were originally engaged in back-end development turned to the front-end. In order to make JavaScript closer to the syntax of some back-end languages ​​so that developers can adapt faster.

  • The role of the class keyword: used to define a class.

  • Features: The constructor constructor method can be defined in the class.

Note

class syntax is essentially syntax sugar, it is designed for user convenience. You can achieve the same results without using this syntax. The effect is like the constructor learned earlier. In case the user's browser does not support this syntax, this method is not recommended.

Private members

Concept: In the constructor, variables defined using the var keyword are called private members.

Features: After the instance object, it cannot be accessed through "object.member", but private members can be accessed in the member method of the object.

Features: The private member name reflects object-oriented encapsulation.

Help you get JavaScript objects

2. Built-in objects

String objects

  • Review the creation of character data: use a pair of single quotes or double quotes quotation marks.
  • Why can character data be used like objects?

This is because these objects are actually instances of the constructor String, that is, String objects.

  • String object provides some properties and methods for processing strings.

Help you get JavaScript objects

Note

When operating on a string, the processing result is returned directly through the return value of the method. It does not change the string content stored in the String object itself. In the parameters of these methods, the position is an index value, counting from 0, the index value of the first character is 0, and the index value of the last character is the length of the string minus 1.

Take the example of limiting the user name length to 3~10 and not allowing the sensitive word admin to appear.

Help you get JavaScript objects

Number object

Number object is used to process integers, floating point numbers and other numerical values. Commonly used properties and methods are as follows.

Help you get JavaScript objects

Help you get JavaScript objects

is a static member of Number and is accessed directly through the constructor Number, not an instance of Number.

Math object

The Math object is used to perform mathematical operations on numerical values. Unlike other objects, this object is not a constructor and does not need to be instantiated to be used.

Help you get JavaScript objects

Take Math.random() to obtain a random number within a specified range as an example.

The formula is Math.random() * (n - m) m, which means generating a random value greater than or equal to m and less than n

Help you get JavaScript objects

Date object

Date object is used to handle date and time.

Help you get JavaScript objects

Help you get JavaScript objects

Example 1: Get the time and date based on the Date object.

Help you get JavaScript objects

#Example 2: Specify a date based on a Date object.

Help you get JavaScript objects

Example 3: Handle the situation when the set date is unreasonable. For example, setting the month to -1 means December last year, and the month is 12 means January next year.

Help you get JavaScript objects

Case: Making a monthly calendar

Help you get JavaScript objects

Code implementation ideas:

  • Construct a date object on the 1st of the current month.
  • Determine what day of the week the 1st is and write the first line.
  • Write about the rest of the month.

Code implementation

	
	<title>本月月历</title>
	
	
	<p><b>本月月历</b></p>
	<script>
	var thisyear,thismonth,today=new Date();;
	thisyear=today.getFullYear()
	thismonth=today.getMonth();
	
	var imonth,iweekday,iday,nextday;
	document.write("<table align=center border=1><tr align=center bgcolor=#fff00>")
	document.write("<td>周日<td>周一<td>周二<td>周三<td>周四<td>周五<td>周六")
	document.write("<tr>")
	nextday=1;
	var thisdate=new Date(thisyear,thismonth,nextday)
	for (iday=0;iday<=6;iday++){
	if (thisdate.getDay() > iday) {
	document.write("<td>");
	document.write("")
	}
	else {
	if (thisdate.getMonth()== today.getMonth()&&thisdate.getDate()== today.getDate() &&thisdate.getFullYear()== today.getFullYear() ){
	document.write("<td><font color=red><b>")
	document.write(nextday)
	document.write("")
	}
	else {
	document.write("<td><b>");
	document.write(nextday);
	document.write("");
	}
	nextday=nextday+1;
	thisdate.setDate(nextday);
	}
	}
	
	document.write("");
	document.write("<tr>")
	iweekday=1
	while(thisdate.getMonth() == thismonth ){
	if (thisdate.getMonth()== today.getMonth()&&thisdate.getDate()== today.getDate() &&thisdate.getFullYear()== today.getFullYear() ){
	document.write("<td><font color=red><b>")
	document.write(nextday)
	document.write("")
	}
	else{
	document.write("<td><b>")
	document.write(nextday)
	document.write("")
	}
	nextday=nextday+1;
	iweekday=iweekday+1;
	if (iweekday>7 ){
	iweekday=1;
	document.write("");
	}
	thisdate.setDate(nextday);
	}
	
	</script>
	
	
	

Related recommendations: javascript learning tutorial

The above is the detailed content of Help you get JavaScript objects. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 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.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 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.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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 Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools