Home Web Front-end JS Tutorial Minimalist method to complete JavaScript encapsulation and inheritance

Minimalist method to complete JavaScript encapsulation and inheritance

Nov 30, 2017 am 09:25 AM
javascript js inherit

In this article, we are going to talk about a relatively new knowledge for beginners: writing JavaScript classes in a minimalist way. The "minimalist approach" is the work of Dutch programmer Gabor de Proposed by Mooij, this method does not use this and prototype, and the code is very simple to deploy. This is probably why it is called the "minimalist method". The following will introduce how to use the minimalist method to complete JavaScript encapsulation and inheritance. I hope it will be helpful to everyone.

1. Encapsulation

First of all, it also uses an object to simulate a "class". In this class, define a constructor createNew() to generate instances.

var Cat = {
    createNew: function(){
      // some code here
    }
};
Copy after login


Then, in createNew(), define an instance object and use this instance object as the return value.

var Cat = {
     createNew: function(){
       var cat = {};
       cat.name = "大毛";
       cat.makeSound = function(){ alert("喵喵喵"); };
       return cat;
     }
 };
Copy after login

When used, call the createNew() method to get the instance object.

var cat1 = Cat.createNew();
cat1.makeSound(); // 喵喵喵
Copy after login


The advantage of this method is that it is easy to understand, has a clear and elegant structure, and conforms to the traditional "object-oriented programming" construct, so the following features can be easily deployed.

2. Inheritance

Let one class inherit another class, which is very convenient to implement. Just call the latter's createNew() method in the former's createNew() method.
First define an Animal class:

var Animal = {
    createNew: function(){
      var animal = {};
      animal.sleep = function(){ alert("睡懒觉"); };
      return animal;
    }
};
Copy after login


Then, in Cat’s createNew() method, call Animal’s createNew() method

var Cat = {
     createNew: function(){
       var cat = Animal.createNew();
       cat.name = "大毛";
       cat.makeSound = function(){ alert("喵喵喵"); };
       return cat;
     }
 };
Copy after login


The Cat instance obtained in this way will inherit the Animal class.

var cat1 = Cat.createNew();
cat1.sleep(); // 睡懒觉
Copy after login


##3. Private properties and private methods

In the createNew() method, as long as it is not defined on the cat object Methods and properties are private.

var Cat = {
    createNew: function(){
      var cat = {};
      var sound = "喵喵喵";//私有属性
      cat.makeSound = function(){ 
     alert(sound); 
    };
      return cat;
    }
};
Copy after login


The internal variable sound in the above example cannot be read externally. It can only be read through the public method makeSound() of cat.

var cat1 = Cat.createNew();
alert(cat1.sound); // undefined
Copy after login


4. Data sharing

Sometimes, we need all instance objects to be able to read and write the same internal data. At this time, just encapsulate the internal data inside the class object and outside the createNew() method.

var Cat = {
    sound : "喵喵喵",
    createNew: function(){
      var cat = {};
      cat.makeSound = function(){ alert(Cat.sound); };
      cat.changeSound = function(x){ Cat.sound = x; };
      return cat;
    }
};
Copy after login


Then, generate two instance objects:

var cat1 = Cat.createNew();
var cat2 = Cat.createNew();
cat1.makeSound(); // 喵喵喵
Copy after login


At this time, if one instance object modifies the shared data, the other instance object will also be affected.

cat2.changeSound("啦啦啦");
cat1.makeSound(); // 啦啦啦
Copy after login
Minimalism looks beautiful, but it also has shortcomings. First of all, instanceof cannot be used to determine the class to which an object belongs, "cat1 instanceof Cat" cannot pass. In addition, although minimalism gets rid of the shortcomings of using the prototype chain (properties cannot be private, creating and inheriting objects is not intuitive), it also exposes the disadvantages of not using the prototype chain: every time an instance is generated, it must For repeated content, it will occupy more memory.

The above content is about the minimalist method of writing JavaScript. I hope it will be helpful to everyone's work.

Related recommendations:

JavaScript object-oriented (minimalist approach)_js object-oriented

Methods for handling JavaScript exceptions

JavaScript simulation Introduction to three ways to implement encapsulation and their differences

The above is the detailed content of Minimalist method to complete JavaScript encapsulation and inheritance. 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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks 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)

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

'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

The AI ​​era of JS is here! The AI ​​era of JS is here! Apr 08, 2024 am 09:10 AM

Introduction to JS-Torch JS-Torch is a deep learning JavaScript library whose syntax is very similar to PyTorch. It contains a fully functional tensor object (can be used with tracked gradients), deep learning layers and functions, and an automatic differentiation engine. JS-Torch is suitable for deep learning research in JavaScript and provides many convenient tools and functions to accelerate deep learning development. Image PyTorch is an open source deep learning framework developed and maintained by Meta's research team. It provides a rich set of tools and libraries for building and training neural network models. PyTorch is designed to be simple, flexible and easy to use, and its dynamic computation graph features make

See all articles