1

Consider I have class

 function home {}{
   this.door=function(){},
   this.tiles=function(){}
 }

I have to add some message after it's methods are called using this library called meld js (https://github.com/cujojs/meld/blob/master/docs/api.md#meldafter)

my try

var allMethods = new home();

   Object.keys(allMethods).forEach(function(k){

       aop.after(Object.prototype,key,function(){
            console.log('Dont use me i am old')
       });
  })

is this a right approach ?

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
jsduniya
  • 2,464
  • 7
  • 30
  • 45
  • Regarding the `AOP` tag, wrapping and reassigning already declared functionality (be it functions or methods) misses any aspect of _AOP_. Any language which wants to qualify for the latter has to provide abstraction levels for at least `Joinpoint`, `Advice` and `Aspect`. The use case described by the OP should be referred to as method modification, and JavaScript of cause is well suited for this scenario and could easily provide a complete `target`/`context` aware toolset of method modifiers like `around`, `before`, `after`, `afterThrowing` and `afterFinally` via `Function.prototype`. – Peter Seliger Sep 14 '22 at 17:06

1 Answers1

1

Your approach is correct but you have several errors in your code. First, the home function should have () instead of {}:

function home() {
    this.door=function(){},
    this.tiles=function(){}
}

Second, in your AOP code you need to provide the object to the after() method and not the prototype.

var allMethods = new home();
Object.keys(allMethods).forEach(function(k){
    aop.after(allMethods,k,function(){
        console.log('Dont use me i am old')
    });
})

(Also you need to use variable k and not key since that's the one defined in the forEach method)

If you'll run one of the methods you'll get the wished output.

allMethods.door() // result 'Dont use me i am old'
Avi L
  • 1,558
  • 2
  • 15
  • 33