JavaScript扩充基本类型的方法与技巧

作者:小括号时间:2026-10-23 21:11:41浏览:79

本文详解如何在JavaScript中扩充基本类型,包括通过Function.prototype.method统一添加方法、为Number添加integer取整、为String添加trim去空格,以及利用new和superior实现对象创建与父方法调用的进阶技巧。

JavaScript扩充基本类型的方法与技巧

利用Function.prototype扩展方法可使该方法应用于所有函数。

通过给Function.prototype添加method方法,后续为对象添加方法时无需再手动输入prototype。


Function.prototype.method=function(name,func){
  this.prototype[name]=func;
  return this;
}

JavaScript增加整数类型

一、JavaScript增加整数类型

JavaScript未提供专门的整数类型,但有时仅需提取数字的整数部分。

可向Number.prototype添加integer方法。

inter()方法依据数字正负性,决定调用Math.ceil或Math.floor。


Number.method('integer',function(){
  return Math[this<0?'ceil':'floor'](this);
});
document.writeln((-10/3).integer());//-3

JavaScript缺少一个移除字符串首尾空白的方法

二、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前缀去调用一个函数

使用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

superior


Object.method('superior',function(name){ //传入方法名name
  var that=this,method=that[name]; 
  return function(){
    return method.apply(that,argumetns);
  }
});

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

作者最新文章