Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why stop using classes in JavaScript

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Why stop using classes in JavaScript? I believe many inexperienced people don't know what to do about it. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

For many years, OOP (object-oriented programming) has been the de facto standard in software engineering. The concepts of class, polymorphism, inheritance and encapsulation dominate the development process and revolutionize it. But everything has an expiration date, including programming examples. I'll discuss why classes were introduced in the first place, why using classes in JavaScript is a bad idea, and some alternatives.

Classes before ES6

Even though the class keyword has been added to JavaScript since ES6 (ECMAScript 2015), people still use classes. The method of implementation is constructor and prototype delegate. To illustrate exactly what I mean, I will implement the same class in both ES5 and ES6 environments. Consider a Car and SportsCar class that inherits from Car. Both have brand (make), model (model) attributes and boot mode (start), but SportsCar also has a turbocharging (turbocharged) attribute and overrides the startup mode (start).

/ / "class" declares function Car (make, model) {this.make = make; this.model = model;} / / Startup method Car.prototype.start = function () {console.log ('vroom');} / / overrides the toString method Car.prototype.toString = function () {console.log (' Car -'+ this.make +'-'+ this.model) } / / inherit instance function SportsCar (make, model, turbocharged) {Car.call (this, make, model); this.turbocharged = turbocharged;} / / actual inheritance logic SportsCar.prototype = Object.create (Car.prototype); SportsCarSportsCar.prototype.constructor = SportsCar; / / override startup method SportsCar.prototype.start = function () {console.log ('VROOOOM') } / / now test course classes var car = new Car ('Nissan',' Sunny'); car.start (); / / vroom console.log (car.make); / / Nissan var sportsCar = new SportsCar ('Subaru',' BRZ', true); sportsCar.start (); / / VROOOOM console.log (car.turbocharged); / / true

As you may have guessed, the Car (line 2) and SportsCar (line 18) functions are constructors. Use this keyword to define the property and use new to create the object itself. If you are not familiar with prototype, this is a special property that every JS object must delegate common behavior. For example, the prototype of an array object has functions that you may be familiar with: map,forEach,find, etc. The string prototype has functions such as replace,substr, etc.

After you create the Car object on line 33, you can access its properties and methods. The call that starts at line 34 results in the following:

The JS engine requires the car object to provide a value with the key start.

The object responded that it did not have such a value.

The JS engine asks the car.prototype object for a value that begins with the key start.

Car.prototype returns the start function that the JS engine executes immediately.

The operation of accessing the make and model properties is similar, except that they are defined directly on the car object, not the prototype.

Inheritance is a bit tricky, which is handled on lines 24-25. The most important function here is the Object.create function, which takes an object and returns a brand new object, whose prototype is set to the object passed as an argument. Now, if the JS engine does not find a value on the sportsCar object or sportsCar.prototype, it will look up that sportsCar.prototype.prototype is the prototype of the Car object.

ES6 Class keyword

With the release of ES6 in 2015, the long-awaited class keyword appears in JavaScript. This is done at the request of the community many times because people are not used to object-oriented languages. But they overlooked an important issue.

JavaScript doesn't know what a class is

JavaScript is not an object-oriented language, it is not designed to be such a language, and the concept of classes is definitely not applicable to it. Although everything in JS is indeed objects, these objects are different from objects in Java or C#. In JS, an object is just an Map data structure with some complex lookup process. okay. When I say everything is an object, I mean it: even functions are objects. You can check through the following code snippet:

Function iAmAnObject () {} console.log (iAmAnObject.name); / / iAmAnObject console.log (Object.keys (iAmAnObject)); / / Array []

Okay, everything is fine, but how does the class keyword work? I'm glad you asked. Do you remember the previous Car and SportsCar examples? Well, the class keyword is just the most important grammar sugar. In other words, the class produces the same code conceptually and is used only for aesthetic and readability purposes. As I promised earlier, this is an example of these same classes in ES6:

Class Car {constructor (make, model) {this.make = make; this.model = model;} start () {console.log ('vroom');} toString () {console.log (`Car-${this.make}-${this.model} `);} class SportsCar extends Car {constructor (make, model, turbocharged) {super (make, model); this.turbocharged = turbocharged } start () {console.log ('VROOOOM');}} / / actual usage remains the same var car = new Car (' Nissan', 'Sunny'); car.start (); / / vroom console.log (car.make); / / Nissan var sportsCar = new SportsCar (' Subaru', 'BRZ', true); sportsCar.start (); / / VROOOOM console.log (car.turbocharged); / / true

These examples are the same and produce the same results, and interestingly, they generate (almost) the same code in the background.

Why not?

You should now understand what classes are in JS and how they work. Now, with all this knowledge, I can explain why using classes in JS is a bad idea.

Binding problem. Because the class constructor works closely with this keyword, it can introduce potential binding problems, especially if you try to pass your class method as a callback to external routines (Hello, React developer).

Performance issues. Because of the implementation of classes, it is well known that they are difficult to optimize at run time. Although we enjoy high-performance machines at the moment, the fact that Moore's Law is disappearing can change all that.

Private variables. First of all, one of the biggest advantages and main reasons for private variables is that classes do not exist in JS.

A strict hierarchy. Classes directly introduce top-to-bottom order, making changes more difficult to implement, which is unacceptable in most JS applications.

Because the React team will tell you not to do it. Although they have not explicitly abandoned class-based components, they are likely to do so in the near future.

All of these problems can be mitigated through JS objects and prototype delegates. JS offers so many things that classes can do, but most developers turn a blind eye to it. If you want to really master JS, you need to accept its ideas and get rid of dogmatic thinking.

After reading the above, do you understand why you want to stop using class methods in JavaScript? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report