'How to return the old value of an overridden property of HTMLElement?

I use the following method to override an HTMLElement property:

Object.defineProperty(HTMLElement.prototype, "style", {
    get: function () {
        var newValue = "some style...";
        return newValue;
    }
});

in the above example, I want to change the style property of HTMLElements. However, I want to return not overridden property (or the native property) in some cases. So far I have tried the following, but it does not work:

var old = HTMLElement.prototype;
Object.defineProperty(HTMLElement.prototype, "style", {
    get: function () {
        if (someCondition) {
            var newValue = "some style...";
            return newValue;
        } else {
            return old.style;
        }
    }
});


Solution 1:[1]

Everything below has only been tested in Firefox 90 esr:

// A function to insert into a style change:
const showFonts = function (val) {
  console.log(val);
  return val;
};

// Save off the functions to be overridden:
var setfont1 = Object.getOwnPropertyDescriptor(CSS2Properties.prototype,'fontFamily').set;
var setfont2 = Object.getOwnPropertyDescriptor(CSS2Properties.prototype,'font-family').set;

// Now override them. 
// Call my function, then the original function:
Object.defineProperty(CSS2Properties.prototype,'fontFamily', 
  { set(val) {   setfont1.call(this,showFonts(val)); },
   enumerable: true,
   configurable: true});
Object.defineProperty(CSS2Properties.prototype,'font-family', 
  { set(val) {  setfont2.call(this,showFonts(val)); },
   enumerable: true,
   configurable: true});

To override almost anything in JS, including built-in functions, console.log the object that contains it, then dig down in the console to find the labels & arguments.

Then use the 'call' function.

Solution 2:[2]

By assigning

var old = HTMLElement.prototype;

You are just making a pointer of the HTMLElement prototype, which is then overriden. Try instead creating a new prototype from the old one.

var old = Object.create(HTMLElement.prototype);

Checkout: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Passacaglia
Solution 2 SergeGMZ