• 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有问题欢迎与我讨论,共同进步。

  • 相关阅读:
    C语言学习笔记-静态库、动态库的制作和使用
    各种消息队列的对比
    如何使用Jupyter notebook
    Ubuntu16.04配置OpenCV环境
    Docker容器发展历史
    Ubuntu OpenSSH Server
    SpringBoot 系列文章
    SpringBoot 模板 Thymeleaf 的使用
    18、spring注解学习(AOP)——AOP功能测试
    17、spring注解学习(自动装配)——@Profile根据当前环境,动态的激活和切换一系列组件的功能
  • 原文地址:https://www.cnblogs.com/starof/p/6510536.html
Copyright © 2020-2023  润新知