有没有办法在数组上获取get/set行为?我想象这样的事情:
var arr = ['one', 'two', 'three'];
var _arr = new Array();
for (var i = 0; i < arr.length; i++) {
arr[i].__defineGetter__('value',
function (index) {
//Do something
return _arr[index];
});
arr[i].__defineSetter__('value',
function (index, val) {
//Do something
_arr[index] = val;
});
}
Run Code Online (Sandbox Code Playgroud) 我正在努力解决最近出现的问题.假设我们想要并且知道如何在javascript中使用动态getter和setter,更像是php(__ get,__ set)中的那些.但是由于javascript没有全能属性,我们唯一能做的就是提供一个可能的键列表,并迭代只在那些上添加getter和setter,并希望别人都不会来.
但问题到目前为止尚未解决.这样就使我想起了另一个方法是使用一个讨厌的黑客与try和catch,因此只要有一个名字会在一个对象是不确定的使用catch是获取(至少),然后恢复代码,硬,也许毫无意义的事做.但是从这里出现了我的第二个问题,在这样的用途:
console.log(g.someundefinedproperty);
Run Code Online (Sandbox Code Playgroud)
结果将是一个console.log显示的调用undefined,没有异常被抛出.然后它来找我:如果我会使用原始的window.undefinedgetter和setter,毕竟每次我搞砸并拼错一个单词或什么时都必须调用它.
所以我试过了
Object.defineProperty(window, 'undefined', {
get : function ()
{
// functional code, including getting the caller and figuring out
// where we are, and what we have to do... easy :D
console.log('works');
},
set : function ()
{
// some couple more fine hacks here
console.log('this too');
}
});
Run Code Online (Sandbox Code Playgroud)
但不幸的undefined是窗口的属性是configurable : false.尝试的其他黑客正在克隆window除了undefined内部window属性之外的对象.并在新的对象上定义新的 …