Javascript中的动态属性getter / setter?

存储(localStorage,sessionStorage)允许使用任意属性.例如.你可以做

localStorage.foo = 'bar';

代替

localStorage.setItem('foo', 'bar');

我自己的javascript对象可以有相同的行为吗?我想在尝试设置属性时执行一些代码.

注意:我显然知道我可以创建setter,但这对于我事先不知道名字的属性不起作用.

注意#2:在对spec进行一些检查之后,我发现除非已经使用setItem()设置了密钥,否则它并不能保证这将起作用:

The names of the supported named properties on a Storage object are the keys of each key/value pair currently present in the list associated with the object

我也可以自己实现这种行为,只要第一组通过动态定义getter / setter来完成一个方法.

最佳答案 你可以使用
__defineGetter__()
__defineSetter__(),但不幸的是它们是Javascript 1.5的Mozilla扩展,所以它们只在某些浏览器中可用(最新版本的Firefox,Opera和Safari).

More information and some examples here.

除此之外,无法在对象上设置/获取属性时添加自定义行为.

点赞