Ood
Ood

Reputation: 1795

JavaScript: Override get and set but keep native functionality

For testing: I need to override the native access to properties of HTMLElement in JavaScript, but keep the native functionality.

The following code overrides the offsetWidth property of HTMLElement but I can't figure out how to log the result of the native getter.

// How can I call this from within the getter?

var nativeOffsetWidth = HTMLElement.prototype.offsetWidth;

// Overrides the native access

Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
    
    get: () => {

        // This part does not work! I need to access the native property here.

        var value = nativeOffsetWidth.call(this);

        console.log(value);
        return value;
        
    }
    
});

I would also like to modify the result once i can get the correct value.

Thanks in advance!

Upvotes: 2

Views: 500

Answers (1)

You can get the original value of a property using Object.getOwnPropertyDescriptor

Use it like this:

const nativeOffsetWidth = Object.getOwnPropertyDescriptor(
    HTMLElement.prototype,
    'offsetWidth'
).get;
nativeOffsetWidth.call(document.body /* example html element */);

Upvotes: 4

Related Questions