Home Web Front-end JS Tutorial Class and instance implementation methods in JavaScript

Class and instance implementation methods in JavaScript

May 16, 2016 pm 04:18 PM
javascript Example kind

This article mainly introduces the implementation methods of classes and instances in JavaScript. It very cleverly simulates the implementation process of classes and instances. It has certain reference value. Friends in need can refer to it. The details are as follows:

There is no concept of parent class, subclass, or class and instance in JavaScript. It relies entirely on the prototype chain to realize inheritance. When looking for the properties of an object, JavaScript will traverse the prototype chain upward until the corresponding property is found. . There are several ways to make JavaScript simulate the concepts of class and instance.

1. Directly use the constructor to create the object, and use this inside the constructor to refer to the object instance.

function Animal() {  
 this.name = "animal";  
 }  
 Animal.prototype.makeSound = function() {  
 console.log("animal sound");  
 }  
[Function]  
 var animal1 = new Animal();  
 animal1.name;  
'animal'  
 animal1.makeSound();  
animal sound
Copy after login

Look at another example:

function Point(x, y) {  
 this.x = x;  
 this.y = y;  
 }  
 Point.prototype = {  
 method1: function() { console.log("method1"); },  
 method2: function() { console.log("method2"); },  
 }  
{ method1: [Function], method2: [Function] }  
 var point1 = new Point(10, 20);  
 point1.method1();  
method1  
 point1.method2();  
method2
Copy after login

Above, first specify the prototype attribute of a constructor object. Then create a new instance of the object, and then call the prototype specified in method.

2. Use the Object.create() method to create an object

var Animal = {  
 name: "animal",  
 makeSound: function() { console.log("animal sound"); },  
 }  
 var animal2 = Object.create(Animal);  
 animal2.name;  
'animal'  
 console.log(animal2.name);  
animal  
 animal2.makeSound();  
animal sound
Copy after login

This method is simpler than the constructor method, However, private properties and private methods cannot be implemented, and data cannot be shared between instance objects, and the simulation of classes is still not comprehensive enough.

3. Minimalist proposed by Dutch programmer Gabor de Mooij Minimalist approach. Recommended usage.

var Animal = {  
 init: function() {  
 var animal = {};  
 animal.name = "animal";  
 animal.makeSound = function() { console.log("animal sound"); };  
 return animal;  
 }  
 };  
 var animal3 = Animal.init();  
 animal3.name;  
'animal'  
 animal3.makeSound();  
animal sound
Copy after login

Do not use prototype and this, only need to customize a constructor init. The implementation of inheritance is also very simple.

var Cat = {  
 init: function() {  
 var cat = Animal.init();  
 cat.name2 = "cat";  
 cat.makeSound = function() { console.log("cat sound"); };  
 cat.sleep = function() { console.log("cat sleep"); };  
 return cat;  
 }  
 }  
 var cat = Cat.init();  
 cat.name; // 'animal'  
 cat.name2; // 'cat'  
 cat.makeSound(); // 类似于方法的重载  
cat sound  
 cat.sleep();  
cat sleep
Copy after login

Use of private attributes and private methods:

var Animal = {  
 init: function() {  
 var animal = {};  
 var sound = "private animal sound"; // 私有属性  
 animal.makeSound = function() { console.log(sound); };  
 return animal;  
 }  
 };  
 var animal4 = Animal.init();  
 Animal.sound; // undefined 私有属性只能通过对象自身的方法来读取.  
 animal.sound; // undefined 私有属性只能通过对象自身的方法来读取  
 animal4.makeSound();  
private animal sound
Copy after login

As long as the attributes and methods are not defined on the animal object, they are private and cannot be accessed by the outside world.
Between classes and instances, you can Achieve data sharing.

var Animal = {  
 sound: "common animal sound",  
 init: function() {  
 var animal = {};  
 animal.commonSound = function() { console.log(Animal.sound); };  
 animal.changeSound = function() { Animal.sound = "common animal sound changed"; };  
 return animal;  
 }  
 }  
 var animal5 = Animal.init();  
 var animal6 = Animal.init();  
 Animal.sound; // 可以视为类属性  
'common animal sound'  
 animal5.sound; // 实例对象不能访问类属性  
undefined  
 animal6.sound;  
undefined  
 animal5.commonSound();  
common animal sound  
 animal6.commonSound();  
common animal sound  
 animal5.changeSound(); // 修改类属性  
undefined  
 Animal.sound;  
'common animal sound'  
 animal5.commonSound();  
common animal sound  
 animal6.commonSound();  
common animal sound
Copy after login

For example, Animal.sound is a common attribute of classes and instances, which can be regarded as class attributes and class methods.

If an instance modifies the common attribute, Then the common attributes of the class and other instances are also modified accordingly.

To sum up, this is the concept and usage of class and instance simulated in JavaScript. I hope this article will be helpful to everyone’s javascript programming. For more related tutorials, please visit JavaScript Video Tutorial!

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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

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

Learn best practice examples of pointer conversion in Golang Learn best practice examples of pointer conversion in Golang Feb 24, 2024 pm 03:51 PM

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

The relationship between the number of Oracle instances and database performance The relationship between the number of Oracle instances and database performance Mar 08, 2024 am 09:27 AM

The relationship between the number of Oracle instances and database performance Oracle database is one of the well-known relational database management systems in the industry and is widely used in enterprise-level data storage and management. In Oracle database, instance is a very important concept. Instance refers to the running environment of Oracle database in memory. Each instance has an independent memory structure and background process, which is used to process user requests and manage database operations. The number of instances has an important impact on the performance and stability of Oracle database.

'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' 'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' Feb 25, 2024 pm 09:04 PM

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

JavaScript and WebSocket: Building an efficient real-time search engine JavaScript and WebSocket: Building an efficient real-time search engine Dec 17, 2023 pm 10:13 PM

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

How to implement an online electronic signature system using WebSocket and JavaScript How to implement an online electronic signature system using WebSocket and JavaScript Dec 18, 2023 pm 03:09 PM

Overview of how to use WebSocket and JavaScript to implement an online electronic signature system: With the advent of the digital age, electronic signatures are widely used in various industries to replace traditional paper signatures. As a full-duplex communication protocol, WebSocket can perform real-time two-way data transmission with the server. Combined with JavaScript, an online electronic signature system can be implemented. This article will introduce how to use WebSocket and JavaScript to develop a simple online

Instance Overview in Oracle Database Instance Overview in Oracle Database Mar 07, 2024 pm 04:42 PM

Oracle database is one of the world's leading relational database management systems, providing powerful functions and flexibility and is widely used in enterprise-level systems. In Oracle database, instance is a very important concept. It carries the running environment and memory structure of the database and is the key to connecting with users and performing SQL operations. What is an Oracle database instance? An Oracle database instance is a collection of processes created when the database is started, including the memory structure and background processes of the database instance. Examples and

See all articles