Does Javascript really need classes?
Let’s first look at some features of other object-oriented languages with classes (such as Java).
Superclass and subclass
Superclass and Subclass are not to solve the problem of father and son, but to solve the inclusion relationship of classes Yes, we use Sub to represent "subclass" and Sup to represent "parent class", then there is:
Sub Sup
There is a difference. For example, usually we can use subclasses as parent classes, but When recognizing people, we cannot regard the son as the father.
In other words, parent classes and subclasses are not designed to solve the problem of the same methods or attributes between classes.
For example
Some people like to do this:
We need some classes of animals in order to create some moving animals on the screen, but some of the moving animals are in the air Flying and some walking on the road.
So create two parent classes, one is Fly and the other is Walk:
Class Fly{
Fly(){}
}
Class Walk{
Walk(){}
}
Then Lion They (you can also build some other animals walking on the road) belong to the Walk category, and the eagles (you can also build some other animals flying in the sky) belong to the Fly category:
Class Lion extend Walk{
}
Class Eagle extend Fly{
}
Finally create some instances of the Lion and Eagle classes, call the corresponding methods, and there will be some lions and eagles moving on the screen.
But this may not be a good design. For example, tomorrow the boss suddenly hits his head and wants to have an animal called Pegasus. They can fly in the sky, walk on the road, and sometimes fly. Time to walk.
In this case, this solution is completely useless.
Why did this design fail?
Inheritance is conditional, and the subclass must be able to strictly transform upward (become a parent class).
In the above example:
Lion is assumed to be equivalent to a walking animal (Walk), and Eagle is assumed to be equivalent to a flying animal (Fly).
This seems successful because the subclass can be strictly upward casted, but it has hidden dangers.
When a kind of Pegasus intervened, we discovered that lions are actually just "walking animals" and eagles are actually just "flying animals". This does not mean that animals can only fly or walk throughout their lives. , so the Pegasus, which can both fly and walk, cannot find its own home.
This example well proves that subclasses and parent classes are not designed to solve the problem of having the same methods between classes:
Some animals can walk and need to have the method Walk, but this should not be done by the child class. Class and parent class implementation.
Combination
We can solve this problem like this:
Class Lion{
walker = new Walk();
walk(){
return walker.walk();
}
}
Class Eagle{
flyer = new Fly();
fly(){
return flyer.fly();
}
}
Class Pegasus{
walker = new Walk();
flyer = new Fly();
walk(){
return walker.walk();
}
fly(){
return flyer. fly();
}
}
Composition is simply creating objects of the original class inside the new class. So combination is to solve the problem of having the same methods between classes. In this example:
Walk is regarded as "the set of methods that walking animals should have", and similarly Fly is regarded as "the set of methods that walking animals should have", so for Pegasus, we only need Just combine Walk and Fly.
The purpose of inheritance
Inheritance is not the only way to reuse code, but inheritance has its advantages:
Subclasses can be transformed upwards into parent classes.
In this way we can ignore all subclass differences and operate as the same class, for example:
We have methods fn(A), fn(B), these two methods are actually similar, we want Reuse them.
Then we can set up a parent class C, where A is a subclass of C and B is a subclass of C, then fn(C) can be reused on A and B.
Back to Javascript
But back to Javascript, we found that the above example is not true.
Because Javascript itself is a weakly typed language, it does not pay attention to the type of the object it operates before (because it does not need to be compiled). It will only succeed or an error will occur.
At this time, inheritance seems unnecessary. Then the class is also not necessary.
I have been writing JavaScript for 8 years now, and I have never once found need to use an uber function. The super idea is fairly important in the classical pattern, but it appears to be unnecessary in the prototypal and functional patterns. I now see my early attempts to support the classical model in JavaScript as a mistake.
——Douglas Crockford
I have been writing Javascript code for 8 years and I have never found the need to use superclass functions. The idea of superclasses is very important in classical design patterns, but it is not necessary in patterns based on prototypes and functions. I now feel that my early attempts to support classic mode in Javascript were a bad decision.
Safe Environment
Of course, you can manually determine the type and control the type of parameters to provide a safer environment.
For example, PHP, which is also a weakly typed scripting language, has to do this in order to simulate a strongly typed object-oriented language and set up a safe environment:
class ShopProductWriter{
public function write( $shopProduct ){
if( ! ( $shopProduct instanceof CdProduct ) && ! ( $shopProduct instanceof BookProduct ) ){
die( "Input wrong type" );
}
//If the type is correct, execute some code
}
}
— —PHP Objects, Patterns, and Practtice Third Edition . Matt Zandstra
But this is just a very ugly solution.
Classic inheritance syntax sugar implementation
However, classic inheritance is still the method favored by many people. Therefore, YUI, Prototype, Dojo, and MooTools all provide their own implementation solutions.
Among the more common solutions, the syntax is roughly like this:
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
}
});
var Dancer = Person.extend ({
init: function(){
this._super( true );
}
});
var n = new Dancer();
alert(n.dancing ); //true
The most important implementation is the implementation of this._super. In fact, the extend function just reassembles the passed in object and turns it into a prototype object. The new constructor in prototype.
Please see Reference 1 for specific implementation.
The classic inheritance syntax sugar of ECMAScript 6
For class libraries to implement their own implementations, resulting in a large number of classic inheritance syntaxes, the ECMA organization seems not satisfied, and they are trying to add more intuitive ones to ECMAScript 6 Classic inheritance syntax sugar:
class Animal {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
bark() {
console.log("Woof!");
}
}
Summary
Actually, classic inheritance is not necessary in Javascript.
However, because many people like the classic inheritance model, related syntactic sugar is provided in the new version of ECMAScript 6.
However, in China, the widespread use of this syntactic sugar on the front end should be a distant story...
Quiz2
What about Javascript-specific inheritance?
Prototypal inheritance
Prototypal inheritance does not solve the collection inclusion relationship in classic inheritance. In fact, prototypal inheritance solves the subordination relationship. The mathematical expression is:
Sub. prototype ∈ Sup
Child constructor (subtype) prototype is an instance object built by a parent constructor (parent type). The prototype is actually something that needs to be shared among subtype instances:
function Being(){
this.living = true;
}
Being.prototype.walk = function(){
alert("I' m walking");
};
function Dancer(){
this.dancing = true;
}
Dancer.prototype = new Being();
Dancer.prototype.dance = function(){
alert ("I'm dancing");
};
var one = new Dancer();
one.walk();
one.dance();
Using borrowing, parasitism and other technologies can produce many different inheritance effects, but these technologies are only to solve some public and non-public issues of attributes and methods in prototype inheritance. Due to space issues, we will not discuss it further. If you are interested, you can refer to the relevant content of "Javascript Advanced Programming".
Thinking Questions
1. If the question about Pegasus at the beginning of the article is written in Javascript, how should it be designed? For example, we have the following two types:
function Walk() {
this.walk = function(){
//walk
};
}
function Fly(){
this.fly = function(){
/ /fly
};
}

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)
