有没有办法在 defineProperty 中捕获 Javascript 集合函数,执行一些逻辑,然后决定是否实际允许调用原始集合函数?
例子
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);
}
}