javascript 是允许给基本类型扩充功能的。例如,可以通过对object.prototype增加方法,可以让该方法对所有的对象都可用。 这样的方式对函数,数组,字符串,数字,正则表达式和布尔值同样适用。
例如,可以通过对Function.prototype 增加方法对所有的函数可用:
Function.prototype.method = function(name, func) { this.prototype[name] = func; return this;
}
通过给Function.prototype 增加method方法,之后再增加方法直接调用mehod方法即可,而不必再写prototype。例如,JavaScript没有整形类型,我们可以通过给Number.prototype增加一个integer方法类实现。
Number.method("integer", function(){ return Math[this <p>通过给基本类型增加方法,可以极大提高语言的表现力。因为JavaScript原型继承的动态本质,新的方法立刻被赋予到所有的对象实例上,包括在方法被增加之前就创建好的对象。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13505" title="FilePond 灵活的 JavaScript 文件上传库"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e695c2374.jpg" alt="FilePond 灵活的 JavaScript 文件上传库" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13505" title="FilePond 灵活的 JavaScript 文件上传库" class="overflowclass">FilePond 灵活的 JavaScript 文件上传库</a>
<p class="overflowclass">FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13505" title="FilePond 灵活的 JavaScript 文件上传库" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>由于基本类型的原型是公用结构的,因此在使用类库的时候一定要小心。一个保险的做法就是只在确定没有该方法的时候才添加它,例如:</p><pre class="brush:js;toolbar:false">Function.prototype.method = function(name, func) { if (!this.prototype(name)) { this.prototype[name] = func;
} return this;
};
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










