Léo*_*Léo 1 javascript jquery function
我使用javascript.假设我的应用程序中有以下功能:
function verify(cats) {
if ( cats > 20 ) {
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
假设我有一个添加猫的按钮,我可以在每只猫添加后使用该功能.但是,我不喜欢这种方法.
我希望此函数在后台,并在条件为true时自动执行
有办法吗?
使用在每个作业上运行的setter.之前:
var obj = {};
obj.cats = 10;
obj.cats += 30;
verify(obj.cats); // we don't want to call this each time.
Run Code Online (Sandbox Code Playgroud)
后:
var obj = {
_cats : 0, // private
get cats() { return this._cats; },
set cats(num) {
verify(num); // any verification here
this._cats = num;
}
};
Run Code Online (Sandbox Code Playgroud)
之后,您可以这样做:
obj.cats += 10; // will run verification
obj.cats = 15; // same
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用代理,但JS引擎尚未广泛支持这些代理.