したがって、他の関数の前後に関数を追加するためにこのコードを作成しましたが、それを行うためのより良い方法を見つけることができませんでした。eval()を使用する必要があり、それは実際には良い習慣ではありません。最初、私は次のようなことをしようとしました:
Function.prototype.append = function(fn){
eval("this = function(){ ("+this.toString()+").apply(this, arguments); fn.apply(this, arguments); }");
}
hello = function(){
console.log("hello world!");
}
hello(); // hello world!
hello.append(function(){
console.log("bye world!");
});
hello(); // hello world! bye world
しかし、関数自体を変更できないため、機能しませんでした。だから私はこれをしました:
Aspects = new Object();
Aspects.append = function(aspect, fn){
eval(aspect + " = function(){ ("+eval(aspect + '.toString()')+").apply(this, arguments); fn.apply(this, arguments); }");
}
Aspects.prepend = function(aspect, fn){
eval(aspect + " = function(){ fn.apply(this, arguments); ("+eval(aspect + '.toString()')+").apply(this, arguments); }");
}
hello = function(){
console.log("hello world!");
}
hello(); // hello world!
Aspects.append('hello', function(){
console.log("bye world!");
});
hello(); // hello world! bye world!
オブジェクトなどを操作したくないので、すでに宣言されている関数の前後にコードを追加したいだけです