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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。