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

 

 

 

本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/6510536.html有问题欢迎与我讨论,共同进步。

posted @ 2017-03-06 16:32  starof  阅读(585)  评论(0编辑  收藏  举报