dynamic getter and setters - a possibility

三世轮回 提交于 2019-12-05 08:10:34
Bergi

But unfortunately the undefined property of window is configurable: false

This is true only since EcmaScript 5.1. Before, it was overwritable.

what if I would use the original window.undefined getter and setter, after all it must be called every time I screw up and misspell a word or something.

No, it would not have worked. There is a difference between the undefined value and the global variable "undefined". The variable is not evaluated each time a undefined value is encountered (e.g. in typeof (void 0)), only when you use it explicitly (such as in g.someprop === undefined).

Any ideas how to solve the dynamic getters and setters problem?

There is only one solution: Proxies. Unfortunately, it is only a harmony draft and currently only supported in Firefox' Javascript 1.8.5.

See also Is there an equivalent of the __noSuchMethod__ feature for properties, or a way to implement it in JS?, Detect when a new property is added to a Javascript object? or How to detect when a property is added to a JavaScript object? which implements a polling solution (checking for changes via setInterval).

For a clean solution, you currently have to use an explicit getter function, which you pass the property name (g.get("someundefinedproperty")).

What you're trying to accomplish (a global getter for any undefined property) is outside the scope of cross-browser JavaScript.

The closest functionality would be using __defineGetter__ to add a particular property to all objects:

var o = Object.prototype;
o.__defineGetter__("testo", function() { return "yo in testo"; });
alert({}.testo);
alert((new Date()).testo);

http://jsfiddle.net/NLCvs/2/

This may be useful if you can predict the name of possibly undefined properties ahead of time. Even so it's quite hacky and bad form to add an accessor to all objects for a property that might be undefined.

A better option is to refactor code when an undefined property may be accessed:

function getter(o, n) {
 return typeof o[n] == 'undefined' ? 'some default value' : o[n];
}
var obj = { hello: 'world' };
alert(getter(obj, 'hello'));
alert(getter(obj, 'an_undefined_property'));

An even better option is to use a mixin to set any default properties you will need to access, for instance via jQuery.extend

var defaults = {
 required: 'this property is required'
};
var my_object = {
 something_else: 'this is something else'
};
var o = jQuery.extend({}, defaults, my_object);

// o.required === 'this property is required'
// o.something_else === 'this is something else'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!