LoginSignup
1
1

More than 3 years have passed since last update.

javascriptのAOP

Posted at

AOPとは

Aspect Oriented Programming(アスペクト指向プログラミング)アスペクトの略称、プログラムの様々なうまく分離できなところを、アスペクトとしてを共通処理を横断的抜き出して統一的に記述することができるような手法です。
Java--768x508.jpg
インメージ図引用元:Spring AOP Tutorial – AOP for Beginners with Examples

javascriptのAOP

色々な手法がありますが、今回はFunction.prototypeを例として紹介させていただきます。

// before関数を定義する
Function.prototype.before = function( functionBefore ) {
  var _this = this;
  // 元々の関数とfunctionBeforeをそれぞれを返すようにする
  return function() {
    functionBefore.apply(this, arguments);
    return _this.apply(this, arguments);
  }
};
// after関数を定義する
Function.prototype.after = function( functionAfter ) {
  var _this = this;
  return function() {
    var result = _this.apply(this, arguments);
    functionAfter.apply(this, arguments);
    return result;
  }
};
// テスト用関数を用意する
var fn = function() {
  console.log('fn is running');
};
// before()とafter()をテスト用関数に「追加」する
fn = fn.before(function(){
  console.log('start!');
}).after(function(){
  console.log('end!');
});

fn();

結果は以下となります:
console.png

'start!'、'fn is running'、'end!'が順次表示されることが分かりました。

AOPの用途

  • 上記のようなロギング処理
  • トランザクション処理
  • エラー処理

などの共通的な仕組み。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1