Javascript如何實現(xiàn)擴(kuò)充基本類型
可以通過給Function.prototype增加方法來使得該方法對所有函數(shù)可用。
通過給Function.prototype增加一個method方法,下次給對象增加方法的時候就不必鍵入prototype這幾個字符了。
Function.prototype.method=function(name,func){ this.prototype[name]=func; return this;}
一、JavaScript增加整數(shù)類型
JavaScript沒有專門的整數(shù)類型,但有時候確實只需要提前數(shù)字中的整數(shù)部分。
可以給Number.prototype增加一個integer方法。
inter()方法根據(jù)數(shù)字的正負(fù)來判斷是使用Math.ceiling還是Math.floor。
Number.method(’integer’,function(){ return Math[this<0?’ceil’:’floor’](this);});document.writeln((-10/3).integer());//-3
二、JavaScript缺少一個移除字符串首尾空白的方法
String.method(’trim’,function(){ return this.replace(/^s+|s+$/g,’’);});document.writeln(’ ' ’+' neat '.trim() +’ ' ’);//' neat '
基本類型的原型是公用結(jié)構(gòu),所以在類庫混用時務(wù)必小心。一個保險的做法就是只在確定沒有該方法時才添加它。
Function.prototype.method=function(name,func){ if(!this.prototype[name]){ this.prototype[name]=func; } return this;}
new前綴去調(diào)用一個函數(shù)
Function.method(’new’,function () { //創(chuàng)建一新對象,它繼承自構(gòu)造器函數(shù)的原型對象。 var that=Object.create(this.prototype); //調(diào)用構(gòu)造器函數(shù),綁定-this-到新對象上。 var other=this.apply(that,arguments); //如果它的返回值不是一個對象,就返回該對象。 return (typeof other===’object’&&other)||that;});
superior
Object.method(’superior’,function(name){ //傳入方法名name var that=this,method=that[name]; return function(){ return method.apply(that,argumetns); }});
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼2. js select支持手動輸入功能實現(xiàn)代碼3. ASP常用日期格式化函數(shù) FormatDate()4. 網(wǎng)頁中img圖片使用css實現(xiàn)等比例自動縮放不變形(代碼已測試)5. html中的form不提交(排除)某些input 原創(chuàng)6. CSS3中Transition屬性詳解以及示例分享7. vue使用moment如何將時間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時間格式8. python 如何在 Matplotlib 中繪制垂直線9. jsp文件下載功能實現(xiàn)代碼10. 開發(fā)效率翻倍的Web API使用技巧
