use*_*599 5 javascript prototype-chain
很多时候,我编写的 JavaScript 与其他脚本一起运行或者可能包含其他脚本。有时,这些脚本可能会更改我可能在代码中使用的原始对象的原型。
有没有一种方法可以在 JavaScript 中声明我的原始数据类型,以便在原型被修改时重置原型?或者让我的脚本可以在一个单独的范围内运行,其中原语的原型不会被修改?
// evil script code modify primative on prototype
Boolean.prototype.toString = function() {
return true;
}
let flag = false;
console.log(flag.toString());
// I would expect false to be printed, but because the prototype of the primative if overridden
// the primative value would be wrapped with the Boolean object
// and call the modified toString method and would output true.Run Code Online (Sandbox Code Playgroud)
有什么方法可以确保我的代码在单独的范围内运行,或者有什么方法可以声明我的变量或重置原型以避免这些类型的问题?
小智 -3
恢复布尔原型原来的toString方法
Boolean.prototype.toString = function() {
return Boolean(this) ? 'true' : 'false';
};
let flag = false;
console.log(flag.toString());
Run Code Online (Sandbox Code Playgroud)
请尝试这个..
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |