1. 程式人生 > 程式設計 >Javascript如何實現擴充基本型別

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);
  }
});

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。