Search code examples
javascriptpropertiespseudo-class

How to access this variable in Object.defineProperty value flag?


I'm attempting to find a way to initialize a property value that is appended to all instances of a JavaScript pseudoclass with localized value references without the need to manually iterate over every instance, as an example the following code:

function A() {
    this.a = '0';
}

var a = new A();
var b = new A();

document.write(a.a + a.b + a.c + '<BR />');

A.prototype.b = '1';
Object.defineProperty(A.prototype, 'c', {
    writable: true,
    value: (function() { return(this.a + '|'); })()
});

document.write(a.a + a.b + a.c + '<BR />');

b.c = '3';

document.write(a.a + a.b + a.c + '<BR />');
document.write(b.a + b.b + b.c + '<BR />');

Outputs:

0undefinedundefined
01undefined|
01undefined|
013

But under the desired condition would output:

0undefinedundefined
010|
010|
013

Edit:

For clarification, the value should be initialized to the properties of the object accessed via "this." when the property is appended to the object, not in a delayed manner on a get or set call and without using additional local properties.


Solution

  • You seem to want a getter function that dynamically computes the value from the a property:

    Object.defineProperty(A.prototype, 'c', {
        get: function() {
            return(this.a + '|');
        },
        set: function(x) { // overwritable:
            // create normal property directly on the object (not on the prototype)
            Object.defineProperty(this, 'c', {
                value: x,
                writable: true
            });
        }
    });
    

    Your current code works like

    A.prototype.c = (function() { return(this.a + '|'); })(); // IEFE
    

    where this is the global object and a of course undefined.