In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to achieve AOP programming in JavaScript", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve AOP programming in JavaScript" article.
Introduction to AOP
The main function of AOP (aspect-oriented programming) is to extract some functions that have nothing to do with the core business logic module, which usually include log statistics, security control, exception handling and so on. After these functions are extracted, they are incorporated into the business logic module by the way of "dynamic weaving".
Aspect-oriented programming gives us a way to inject code into existing functions or objects without modifying the target logic.
Although not necessary, the injected code means crosscutting concerns, such as adding logging capabilities, debugging metadata, or other less generic but can inject additional behavior without affecting the content of the original code.
To give you an appropriate example, suppose you have written the business logic, but now you realize that you have not added the logging code. The usual method is to centralize the log logic into a new module, and then add log information function by function.
However, if you can get the same logger and inject the program at a specific node during the execution of each method you want to record, it will certainly bring you a lot of convenience. isn't it?
Facets, notices, and pointcuts (what, when, where)
To formalize the above definition, let's take the logger as an example to introduce three concepts about AOP. If you decide to study this paradigm further, these will help you:
Aspect (what is it): this is the "aspect" or behavior that you want to inject into your object code. In our context (JavaScript), this refers to a function that encapsulates the behavior you want to add.
Notification (when): when do you want this aspect to be executed? the Notification specifies some common moments when you want to execute the aspect code, such as "before", "after", "around", "whenThrowing", and so on. In turn, they refer to the point in time associated with code execution. For parts referenced after code execution, this section intercepts the return value and may overwrite it as needed.
Pointcut (where): they refer to the location of the aspect you want to inject in your target code. In theory, you can explicitly specify any location in the object code to execute the facet code. This is actually not realistic, but you can potentially specify, for example, "all methods in my object," or "just this particular method," or we can even use things like "all methods that start with get_."
With these explanations, you will find it relatively easy to create an AOP-based library to add logging logic to existing OOP-based business logic (for example). All you have to do is replace the existing matching method of the target object with a custom function that adds aspect logic at the appropriate point in time and then calls the original method.
Basic realization
Because I am a visual learner, I think it will be a long process to show a basic example of how to implement a faceted approach to add AOP-based behavior.
The following example illustrates how easy it is to implement it and the benefits it brings to your code.
`/ * * Helper function used to get all methods in an object * / const getMethods = (obj) = > Object.getOwnPropertyNames (Object.getPrototypeOf (obj)) .filter (item = > typeof obj [item] = "function") / * * replace the original method with a custom function This function will call our section * / function replaceMethod (target, methodName, aspect, advice) {const originalCode = target [methodName] target [methodName] = (... args) = > {if (["before", "around"] .aspects (advice)) {aspect.apply (target, args)} const returnedValue = originalCode.apply (target, args) if (["after", "around"] .aspects (advice)) {aspect.apply (target) Args)} if ("afterReturning" = = advice) {return aspect.apply (target, [returnedValue])} else {return returnedValue} module.exports = {/ / the main method for export: injecting sections into the target inject at the time and location needed: function (target, aspect, advice, pointcut, method = null) {if (pointcut = "method") {if (method! = null) {replaceMethod (target, method, aspect) Advice)} else {throw new Error ("Tryin to add an aspect to a method, but no method specified")}} if (pointcut = = "methods") {const methods = getMethods (target) methods.forEach (m = > {replaceMethod (target, m, aspect, advice)})} `
Very simple, as I mentioned, the above code does not cover all the use cases, but it should be sufficient to cover the next example.
But before we move on, notice the replaceMethod function, which is where the magic takes effect. It can create a new function, and it can also determine when we call our section and what to do with its return value.
Next, explain the use of this library:
`const AOP = require (". / aop.js") class MyBussinessLogic {add (a, b) {console.log ("Calling add") return a + b} concat (a, b) {console.log ("Calling concat") return a + b} power (a) B) {console.log ("Calling power") return a * * b} const o = new MyBussinessLogic () function loggingAspect (... args) {console.log ("= Calling the logger function = =") console.log ("Arguments received:" + args)} function printTypeOfReturnedValueAspect (value) {console.log ("Returned type:" + typeof value)} AOP.inject (o, loggingAspect, "before", "methods") AOP.inject (o, printTypeOfReturnedValueAspect, "afterReturning") "methods") o.add (2) o.concat ("hello", "goodbye") o.power (2, 3) `
This is just a basic object with three methods, nothing special. We want to inject two general aspects, one to record the received attributes and the other to analyze their return values and record their types. Two sections and two lines of code (six lines of code are not required).
This example ends here, and here is the output you will get:
Https://camo.githubusercontent.com/f18ef187f4acddab8df097c8aa4521d632e17759bc1c0831a22ada934388d7b5/68747470733a2f2f63646e2d696d616765732d312e6d656469756d2e636f6d2f6d61782f323030302f312a394b5a42774f6262714145754a4176314757537279672e706e67
Advantages of AOP
After knowing the concept and purpose of AOP, you can guess why people want to use aspect-oriented programming, but let's do a quick summary:
A good way to encapsulate crosscutting concerns. I like encapsulation very much because it means it's easier to read and maintain code that can be reused throughout the project.
Flexible logic. When injecting aspects, the logic implemented around notifications and pointcuts can provide you with a lot of flexibility. On the other hand, it helps you to dynamically turn on and off different aspects of code logic (intentional puns).
Reuse aspects across projects. You can think of aspects as components, small, decoupled pieces of code that can be run anywhere. If you write aspect code correctly, you can easily share them in different projects.
The main problems of AOP
Because not everything is perfect, this paradigm has been opposed by some critics.
The main problem they raised is that its main advantages actually hide the logic and complexity of the code and may have side effects in less clear cases.
If you think about it, they have a point. AOP gives you a lot of power to add extraneous behaviors to existing methods, or even replace their entire logic. Of course, this may not be the exact reason for introducing this paradigm, and it is certainly not the intention of the example I provided above.
However, it does allow you to do whatever you want, coupled with a lack of understanding of good programming practices, can lead to great confusion.
In order not to sound too old-fashioned, I repeat what Uncle Ben said:
The greater the ability, the greater the responsibility.
If you want to use AOP correctly, you must understand the best practices of software development.
In my opinion, just because you may cause a lot of damage after using this tool, it is not enough to say that this tool is bad, because it also brings a lot of benefits (that is, you can extract a lot of common logic to a centralized location and inject it with a single line of code wherever you need it). For me, this is a powerful tool that is worth learning and definitely worth using.
Aspect-oriented programming is a perfect complement to OOP, especially because of the dynamic nature of JavaScript, which can be easily implemented (such as the code demonstration here). It provides powerful capabilities to modularize and decouple a large amount of logic, which can even be shared with other projects later.
Of course, if you don't use it correctly, you will make a mess of things. But you can definitely use it to simplify and clean up a lot of code. That's what I think of AOP. What about you? Have you ever heard of AOP? Have you ever used it before? Please leave a message below and share your thoughts!
The above is about the content of this article on "how to achieve AOP programming in JavaScript". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.