function attachAfterReturning(obj,name,advice) {
var old = obj[name];
obj[name] = function(){
var result = old.apply(this,arguments);
advice.call(this,result);
return result;
}
}
It’s where you can request that something is done at different stages of a method being called.
What the above function does, is to replace the method obj[name] so that the return value is returned not just once, but twice. The first place the first is returned is to the advice method, and the second place the result is returned is to whatever calls obj[name]
For example, you have a duck that when asked to speak, it goes “quack”.
var duck = {
'speak': function () {
return 'Quack!';
}
};
alert(duck.speak());
// An alert appears saying 'Quack!'
What it says can also appear in a log, by using the attachAfterReturning function.
In your example, an array is returned from the speak function, but javascript when used with a string, such as in the logDuck function, javascript converts the array to a comma-separated string for you.
I suspect that the speak function in this example should more correctly return just a string, instead of an array.
Thanks. For some reason I now feel that I should start singing “A spoonful of sugar helps the medicine go down.”
You’re right there, but the slideshow uses advice.call instead of advice.apply
With the apply method, all of the arguments are given in the array. With the call method, all of the arguments are given as separate function parameters.
I’ve updated the code sections above so that they match the slideshow, which means that this is now no longer an issue.