0

defineProperty で Javascript の set 関数をキャッチし、いくつかのロジックを実行してから、元の set 関数の呼び出しを実際に許可するかどうかを決定する方法はありますか?

var scope = {}; 
scope.myVar = 1;

scope._myVar = scope.myVar; 
Object.defineProperty(scope, "myVar", {  
  get: function(){
    return scope._myVar;
  },
  set: function(val) {
    scope._myVar = val;
    //Do some other work   
  } 
}

//Now when scope.myVar is changed, its setter is invoked 
//I would like to write some code here now that will run even before the
//myVar setter, do some work, and then decide whether to invoke the setter
//or not.  If it decides to not invoke the setter, then it will be as
//though the scope.myVar = ... was never called.

//Psuedo-code
scope._setMyVar = scope.setMyVar;
scope.setMyVar = function(val) {
  //do some work
  var condition = resultOfWorkAbove;

  if(condition) {
    scope._setMyVar(val);
  }
}
4

1 に答える 1