JavaScript原生对象的api有些情况下使用并不方便,考虑扩展基于Object、Function、String、Array扩展,参考了prototype.js的部分实现,做了提取和修改,分享下:

/**** @authors yinshen (shenyin19861216@163.com)* @date        2013-09-05 23:23:25* @version $Id$*/
//Object 扩展
(function() {var FUNCTION_CLASS = '[object Function]',BOOLEAN_CLASS = '[object Boolean]',NUMBER_CLASS = '[object Number]',STRING_CLASS = '[object String]',ARRAY_CLASS = '[object Array]',OBJECT_CLASS = '[object Object]',DATE_CLASS = '[object Date]';function extend(destination, source) {for (var property in source) {destination[property] = source[property];}return destination;}function clone(o,deep) {if (deep === true) {var target = {};for (var property in o) {if (o.hasOwnProperty(property)) {if (Object.isObject(o[property])) {target[property] = Object.clone(o[property],true);} else {target[property] = o[property];}}}return target;} else {return extend({}, o);}}function isElement(object) {return !!(this && object.nodeType == 1);}function isObject(object) {return Object.prototype.toString.call(object) === OBJECT_CLASS;}function isArray(object) {return Object.prototype.toString.call(object) === ARRAY_CLASS;}function isFunction(object) {return Object.prototype.toString.call(object) === FUNCTION_CLASS;}function isString(object) {return Object.prototype.toString.call(object) === STRING_CLASS;}function isNumber(object) {return Object.prototype.toString.call(object) === NUMBER_CLASS;}function isDate(object) {return Object.prototype.toString.call(object) === DATE_CLASS;}function isUndefined(object) {return typeof object === "undefined";}function param(object) {var arr = [];for (var prop in object) {if (object.hasOwnProperty(prop)) {arr.push([encodeURIComponent(prop), "=", encodeURIComponent(object[prop]), "&"].join(""));}}return arr.join("").slice(0, -1);}function each(object,fn) {if(typeof fn ==="undefined"){return;}for (var prop in object) {if (object.hasOwnProperty(prop)) {if (fn(object[prop], prop) === false) {break;}}}}extend(Object, {//extend(Object.prototype, {        extend: extend,clone: clone,isObject: isObject,isElement: isElement,isArray: isArray,isFunction: isFunction,isString: isString,isNumber: isNumber,isDate: isDate,isUndefined: isUndefined,param: param,each: each});})();//String 扩展
Object.extend(String.prototype, (function() {//字符串替换,支持{}和[]function format(o) {return this.replace(/\{(\w+)\}/g, function($1, $2) {return o[$2] !== undefined ? o[$2] : $1;});};//获取字符串长度,区分中文占2个字符function len() {return this.replace(/[^\x00-\xff]/g, '**').length;}function truncate(length, truncation) {length = length || 30;truncation = Object.isUndefined(truncation) ? '...' : truncation;return this.length > length ?this.slice(0, length - truncation.length) + truncation : String(this);}function trim(isLeft) {if (isLeft === true) {return this.replace(/^\s+/, '');} else if (isLeft === false) {return this.replace(/\s+$/, '');}return this.replace(/^\s+/, '').replace(/\s+$/, '');}var htmlDiv=document.createElement("div");function html(escape) {
/*        var replace = ["'", "'", '"', "&quot;", " ", "&nbsp;", ">", "&gt;", "<", "&lt;", "&", "&amp;", ];escape === false && replace.reverse();for (var i = 0, str = this; i < replace.length; i += 2) {str = str.replace(new RegExp(replace[i], 'g'), replace[i + 1]);}return str;*/function encode(){htmlDiv.innerHTML="";return htmlDiv.appendChild(document.createTextNode(this)).parentNode.innerHTML.replace(/\s/g, "&nbsp;");}function decode(){htmlDiv.innerHTML=this;return htmlDiv.innerText;}        var str=this;return escape===false?decode.apply(str):encode.apply(str);}function has(pattern) {return this.indexOf(pattern) > -1;}function startsWith(pattern) {return this.lastIndexOf(pattern, 0) === 0;}function endsWith(pattern) {var d = this.length - pattern.length;return d >= 0 && this.indexOf(pattern, d) === d;}function empty() {return this == '';}function text() {return this.replace(/<\/?[^>]*\/?>/g, '');}function blank() {return /^\s*$/.test(this);}function sprintf(){var i,              result = this,param,reg,length = arguments.length;if (length < 1){return text;}i = 0;while(i < length){result = result.replace(/%s/, '{#' + (i++) + '#}');                 }result.replace('%s', ''); i = 0;while( (param = arguments[i])!==undefined ){ // 0 也是可能的替换数字reg = new RegExp('{#' + i + '#}', 'g')result = result.replace(reg, param);i++;}return result;}function bytes() {var str = this,i = 0,_char,l = 0;while(_char = str.charAt(i++)){l += (_char).charCodeAt().toString(16).length / 2;}return l;}return {format: format,sprintf:sprintf,text: text,len: len,truncate: truncate,trim: String.prototype.trim || trim,html: html, //"&<>".html()==="&amp;&lt;&gt;"    "&amp;&lt;&gt;".html(false)==="&<>"
        has: has,startsWith: startsWith,endsWith: endsWith,empty: empty, //内容为空,连空格都没                        "     ".empty()===falseblank: blank, //没有任何有意义的字符,空格不算    "     ".blank()===truebytes : bytes //计算一个字符串的字节长度
    };
})());//Function 扩展
Object.extend(Function.prototype, (function() {var slice = Array.prototype.slice;function update(array, args) {var arrayLength = array.length,length = args.length;while (length--) array[arrayLength + length] = args[length];return array;}function merge(array, args) {array = slice.call(array, 0);return update(array, args);}function bind(context) {if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;var __method = this,args = slice.call(arguments, 1);return function() {var a = merge(args, arguments);return __method.apply(context, a);}}/*    这东西炫耀的价值大于实用,还是不引入了function curry() {if (!arguments.length) return this;var __method = this, args = slice.call(arguments, 0);return function() {var a = merge(args, arguments);return __method.apply(this, a);}}function uncurry(){var __method=this;return function(){Function.prototype.call.apply(__method,arguments);}}*/function delay(timeout) {var __method = this,args = slice.call(arguments, 1);timeout = timeout * 1000;return window.setTimeout(function() {return __method.apply(__method, args);}, timeout);}function defer() {var args = update([0.01], arguments);return this.delay.apply(this, args);}function before(fn) {var __method = this;return function() {if (fn.apply(this, arguments) === false) {return false;}return __method.apply(this, arguments);}}function after(fn) {var __method = this;return function() {var ret = __method.apply(this, arguments);var args = update([ret], arguments);fn.apply(this, args);return ret;}}function wrap(wrapper) {var __method = this;return function() {var a = update([__method.bind(this)], arguments);return wrapper.apply(this, a);}}return {bind: bind,delay: delay,defer: defer,before: before,after: after,wrap: wrap}
})());//Array扩展
(function() {var arrayProto = Array.prototype,slice = arrayProto.slice;function each(iterator, context) {for (var i = 0, length = this.length >>> 0; i < length; i++) {if (i in this) iterator.call(context, this[i], i, this);}}function last() {return this[this.length - 1];}function clone(deep) {if (deep === true) {return Object.clone.apply(this, arguments);}return slice.call(this, 0);}function map(fn) {var arr = [];this.each(function(v, k) {arr.push( fn(v, k) );});return arr;}Object.extend(arrayProto, {each: Array.prototype.forEach || each,last: last,clone: clone,map: map});
})();

转载于:https://www.cnblogs.com/yinshen/p/3304693.html

Object、Function、String、Array原生对象扩展方法相关推荐

  1. ES6新特性_ES6的对象扩展方法---JavaScript_ECMAScript_ES6-ES11新特性工作笔记040

    然后我们看一下es6中的对象扩展方法 可以看到有个Object.is(120,121); 这个相当于判断是否相等,也就是是否是某个对象. 可以看到120,和121 不相等. 然后120和120相等. ...

  2. String类的对象的方法 格式小结 java 1202

    String类的对象的方法 格式小结 java 1202 定义一个字符串 两种方法可以定义字符串 String 字符串对象 = "内容" String 字符串对象 = new St ...

  3. JavaScript String 对象扩展方法

    /** 在字符串末尾追加字符串 **/ String.prototype.append = function (str) {return this.concat(str); } /** 删除指定索引位 ...

  4. java对象扩展方法_高可扩展的面向对象代码架构是如何设计的

    导语 Java后端程序员的日常工作,大多数可能都是写基于数据库CRUD的Dao层.Manager层.Service层.Controller层,需求来了,就对着这几个层一顿怼代码.调试跑通了,就完事了. ...

  5. jquery的扩展方法介绍

    最近一直在写js,这其中也少不了一位js的主角了jQuery,下面介绍的是jQuery的一些扩展,也就是jQuery的扩展方法,jQuery的扩展方法有两种方式,一种是jQuery本身的扩展方法,另一 ...

  6. jquery扩展方法

    jquery插件的开发包括两种:一种是类级别的插件开发,即给jquery添加新的全局函数,相当于给jquery类本身添加方法. jQuery的全局函数就是属于jquery命名空间的函数,另一种是对象级 ...

  7. 技术图文:C# 语言中的扩展方法

    背景 前段时间,在知识星球立了一个Flag,在总结 Leetcode 刷题的第五篇图文时遇到了扩展方法 这个知识点,于是先总结一下. 1.扩展方法概述 扩展方法能够向现有类型"添加" ...

  8. [C# 基础知识系列]专题十五:全面解析扩展方法

    引言:  C# 3中所有特性的提出都是更好地为Linq服务的, 充分理解这些基础特性后.对于更深层次地去理解Linq的架构方面会更加简单,从而就可以自己去实现一个简单的ORM框架的,对于Linq的学习 ...

  9. 系统类扩展方法,实现对所有类或某种类扩展自定义方法

    扩展方法的格式: 1.必须把扩展方法写在静态类中 2.扩展方法的第一个参数必须加 "this" 修饰 例如,对所有object对象的扩展方法IsEmptyOrNull,判断对象是否 ...

最新文章

  1. html 获取cookie的值,js从Cookies里面取值的简单实现
  2. flappy bird游戏源代码揭秘和下载后续---移植到android真机上
  3. PyCharm修改镜像源无用?
  4. ElementUI项目中怎样引用Jquery
  5. 小程序学习(1):微信开发者工具安装
  6. Flink UI: Flink 1.10 如何查看 数据源 的背压(反压)情况(消费kafka)
  7. WebStorm光标经常自动变为块状解决方案
  8. 123.PHP 周边性能优化
  9. 计算机系统运维服务方案,xx局信息化系统运维服务方案+标准版.doc
  10. python累乘怎么写_Python3 实现列表元素求累和,求累乘
  11. 【cs224n-11】Contextual Word Representations: BERT
  12. paip.突破 网站 手机 验证码 的 破解 总结
  13. idea的使用教程(IntelliJ IDEA)
  14. 公司内网openvpn部署,
  15. 汽车CAN通信基础知识-Java之Socket通信实战
  16. 品牌管理系统(第一个web项目)
  17. 面试官:这波HTTP究极combo,你顶得住吗?
  18. 浏览器-清理页面中js的缓存
  19. kafka SASL认证介绍及自定义SASL PLAIN认证功能
  20. JAVA Set 交集,差集,并集

热门文章

  1. docker拉取镜像查看版本
  2. 基于AT89C52单片机的简易电子琴设计与仿真
  3. word应用:用数学公式编辑器MathType编排公式时的字体大小设置
  4. Hibernate中的级联策略和object references an unsaved transient instance - save the transient instance before
  5. 2019杭州小学入学报名指南
  6. 《启示录:打造用户喜爱的产品》—— 读书笔记
  7. 【黄啊码】我问ChatGPT如何学习PHP语言,它是这么说的
  8. 《网络、群体和市场》习题答案
  9. PoE供电、集中供电、点对点供电各自的优缺点
  10. QQ旋风自动关闭解决方法