Decorator mode

The characteristics of

  • Add new functionality to the object
  • It does not change its original structure and function

introduce

  • Dynamically add new methods or properties to an object during execution. These new methods and properties themselves do not belong to the object. It’s like a plug-in on this object. Press it when you need it, and remove it when you don’t.
  • Unlike inheritance, decorator patterns focus on dynamic assembly of methods. It preserves the execution of the original method and adds methods or attributes where necessary. Decorators, however, can only add, but not change, the details of the original method.
  • But in decorator mode, it’s important to note that how do we circumvent this hijacking by using call/apply
  • Such as checking before the original method is executed. Or after the original method is executed. There is no need to rewrite the code of the original method because it violates the single rule. For later code maintenance is not very convenient.

demo

More detailed code

  • Pair function decoration
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, Initial scale = 1.0 "/ > < title > Function decoration < / title > < / head > < body > < script > Function. The prototype. Before = Function (fn) {var of love = this; return function () { fn.apply(_self); _self.apply(this); }; }; Function.prototype.after = function (fn) { var _self = this; return function () { var ret = _self.apply(this); fn.apply(_self); return ret; }; }; var test = function () { console.log("show 2"); }; test = test.before(function () { console.log("show 1"); }); test = test.after(function () { console.log("show 3"); }); test(); </script> </body> </html>Copy the code
  • Pair parameter decoration
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, Initial scale = 1.0 "/ > < title > parameter decoration < / title > < / head > < body > < script > Function. The prototype. The addParam = Function (fn) {var _self = this; return function () { fn.apply(_self, arguments); return _self.apply(this, arguments); }; }; test = function (param) { return param; }; test = test.addParam(function (param) { param.b = "b"; }); const param = test({ a: "a" }); console.log(param); </script> </body> </html>Copy the code