Javascript如何實現擴充基本類型
可以通過給Function.prototype增加方法來使得該方法對所有函數可用。
通過給Function.prototype增加一個method方法,下次給對象增加方法的時候就不必鍵入prototype這幾個字符了。
Function.prototype.method=function(name,func){ this.prototype[name]=func; return this;}
一、JavaScript增加整數類型
JavaScript沒有專門的整數類型,但有時候確實只需要提前數字中的整數部分。
可以給Number.prototype增加一個integer方法。
inter()方法根據數字的正負來判斷是使用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 '
基本類型的原型是公用結構,所以在類庫混用時務必小心。一個保險的做法就是只在確定沒有該方法時才添加它。
Function.prototype.method=function(name,func){ if(!this.prototype[name]){ this.prototype[name]=func; } return this;}
new前綴去調用一個函數
Function.method(’new’,function () { //創建一新對象,它繼承自構造器函數的原型對象。 var that=Object.create(this.prototype); //調用構造器函數,綁定-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); }});
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. vue實現web在線聊天功能2. JavaEE SpringMyBatis是什么? 它和Hibernate的區別及如何配置MyBatis3. JavaScript實現頁面動態驗證碼的實現示例4. Springboot 全局日期格式化處理的實現5. Java使用Tesseract-Ocr識別數字6. 完美解決vue 中多個echarts圖表自適應的問題7. Python使用urlretrieve實現直接遠程下載圖片的示例代碼8. SpringBoot+TestNG單元測試的實現9. 在Chrome DevTools中調試JavaScript的實現10. 解決Android Studio 格式化 Format代碼快捷鍵問題
