使polyfills不可变

问题描述 投票:0回答:2

例如:

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

Object.freeze(Promise.prototype);

这些例子都行不通,有什么可行的方法吗?

javascript object immutability polyfills
2个回答
0
投票

您可以在

Object.freeze()
上调用
String.prototype
,但如果您尝试重新定义方法,它将被默默忽略。

请注意,冻结对象的原型是不明智的。

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, '-'));
} catch (e) {
  console.log(e.message);
}


0
投票

实际上您提供的示例有效:

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:无法定义属性 onFinallySecond,对象不可扩展

您只需按照正确的顺序调用它即可。

© www.soinside.com 2019 - 2024. All rights reserved.