[英]How to use "String.prototype" in javascript
我想使用 String.prototype 创建一个 function 可以隐藏 js 中的元素。 我的代码写在下面。
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <h1 id="id"></h1> </body> <script> String.prototype.hide = () => { return "style;display=none." } document.getElementById("id");hide(); </script> </html>
这给了我一个错误 Uncaught TypeError: Cannot read properties of null (reading 'hide')
我试图找出如何使用它很长一段时间。 请帮我!!!
如果您要扩充内置原型来执行此操作,扩充Element.prototype
而不是String.prototype
会更有意义,因为您尝试使用hide
的不是字符串,它是HTMLElement
实例(继承自Element
)。
但是增加/扩展内置原型通常不是一个好主意。 很脆弱。 如果同一页面中的两个脚本使用相同的名称,它们会相互干扰。 如果 DOM 稍后获得一个hide
方法,那会弄乱您现有的代码。 等等。最好将元素传递给 function:
function hide(element) { element.style.display = "none"; } setTimeout(() => { hide(document.getElementById("id")); }, 800);
<h1 id="id">Hi there</h1>
但是,如果您这样做,请使用defineProperty
使扩展不可枚举:
Object.defineProperty(Element.prototype, "hide", { value() { this.style.display = "none"; }, writable: true, configurable: true, enumerable: false, // This is the default, but I'm including it for emphasis... }); setTimeout(() => { document.getElementById("id").hide(); }, 800);
<h1 id="id">Hi there</h1>
如果您真的非常想要,您可以在String.prototype
上执行此操作,假设字符串是元素的id
(或元素的选择器)。 例如:
Object.defineProperty(String.prototype, "hide", { value() { const element = document.getElementById(this); if (element) { element.style.display = "none"; } }, writable: true, configurable: true, enumerable: false, // This is the default, but I'm including it for emphasis... }); setTimeout(() => { "id".hide(); }, 800);
<h1 id="id">Hi there</h1>
但我不会那样做。 :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.