Access to the original property value from `__defineGetter__`

Is it possible to access the original property value from a Javascript receiver?

If not, are there other β€œmodern” javascript methods to achieve something similar?

That is, if I have code like this

o = {} o.foo = "bar" o.__defineGetter__("foo", function(){ //can I access the value "bar" here? return "some other value"; }); 

Is it possible to access the value of "bar" from my getter function? Or __defineGetter__ remove a property?

(Context: not a newbie developer, but I have ignored non-browser Javascript for the last 4/5 years and I want to catch up)

+4
source share
3 answers

ECMAscript 262-5 proposed the option of having getters and setters on objects officially defined by the specification. You can configure them either directly in the object literal

 var foo = { get bar() { return "foo"; } }; 

or using Object.defineProperty()

 var foo = { }; Object.defineProperty(foo, 'bar', { get: function() { return "foo"; } }); 

However, the problem remains the same. Overwriting a property will unreasonably overwrite it. What you can do is use prototype chain objects to get properties.


 var foo = { }; foo.bar = 42; Object.defineProperty(Object.getPrototypeOf( foo ), 'bar', { get: function() { return 'overwritten'; }, configurable: true }); console.log( foo.bar ); // 42 delete foo.bar; console.log( foo.bar ); // "overwritten" 
+1
source

No, __defineGetter__ (as well as Object.defineProperty ) overwrites everything old. You will have to cache the old value in an additional variable before "blowing off the property".

Using IEFE as a closure:

 o = {foo: "bar"}; (function(oldval) { o.__defineGetter__("foo", function(){ return "new"+oldval; }); })(o.foo); o.foo; // "newbar" 
+1
source

__defineGetter__ as a shortcut to

 Object.defineProperty(o, "foo", {get : function() { return "some other value"; }, enumerable : true}); 

Thus, the value of o.foo is simply overwritten. To solve this problem, add the additional property o._foo and do not forget about the customizer.

My example:

 var o = {}; Object.defineProperty(o, "foo", { get : function() { return this._foo; }, set : function(value) { this._foo = value; }, enumerable : true}); o.foo = "newbar"; o.foo; //newbar 
+1
source

Source: https://habr.com/ru/post/1442874/


All Articles