skip to Main Content

For example:

Object.defineProperty(Promise.prototype, 'onFinally', {
  get: () => {},
  writable: false,
});

or

Object.freeze(Promise.prototype);

These examples aren’t work, is there a working way?

2

Answers


  1. You can call Object.freeze() on the String.prototype, but if you try to redefine a method, it will silently be ignored.

    Note that freezing an Object’s prototype is ill-advised.

    function padBoth(targetLength, padString) {
      const delta = Math.floor((targetLength - this.length) / 2);
      return delta > 0
        ? this
          .padStart(this.length + delta, padString)
          .padEnd(targetLength, padString)
        : this
    }
    
    String.prototype.padBoth = padBoth;
    console.log('Hello World'.padBoth(20, '-'));
    
    // Without this line, the try-catch (below) will throw
    Object.freeze(String.prototype);
    
    // No error, but does not reassign
    String.prototype.padBoth = undefined;
    try {
      console.log('Hello World'.padBoth(20, '-')); // Works, if frozen
    } catch (e) {
      console.log(e.message);
    }
    Login or Signup to reply.
  2. Actually the example you provided works:

    Object.defineProperty(Promise.prototype, 'onFinally', {
        get: () => { console.log("Retrieved.") }
    });
    
    Promise.prototype.onFinally
    
    Object.freeze(Promise.prototype);
    
    Promise.prototype.onFinally
    
    Object.defineProperty(Promise.prototype, 'onFinallySecond', {
        get: () => { console.log("Retrieved.") }
    });
    

    TypeError: Cannot define property onFinallySecond, object is not extensible

    You just have to call it in the correct order.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search