Object、Function、String、Array原生对象扩展方法
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 = ["'", "'", '"', """, " ", " ", ">", ">", "<", "<", "&", "&", ];
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, " ");
} 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()==="&<>" "&<>".html(false)==="&<>"
has: has,
startsWith: startsWith,
endsWith: endsWith,
empty: empty, //内容为空,连空格都没 " ".empty()===false
blank: blank, //没有任何有意义的字符,空格不算 " ".blank()===true
bytes : 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
});
})();
Object、Function、String、Array原生对象扩展方法的更多相关文章
- jQuery对象扩展方法(Extend)深度解析
1.这几天在写自己的Js工具类库,所以在编写对象扩展方法,参考了jQuery的对象扩展方法,在编写该方法前,需要掌握js深拷贝和浅拷贝的相关知识,下面是jQuery3.2.1版本对象扩展方法的源码: ...
- 给 string 添加一个 GetInputStream 扩展方法
有时候,我们须要读取一些数据,而无论这数据来源于磁盘上的数据文件,还是来源于网络上的数据.于是.就有了以下的 StringExtensions.cs: using System; using Syst ...
- 为Jquery类和Jquery对象扩展方法
转:https://www.cnblogs.com/keyi/p/6089901.html jQuery为开发插件提拱了两个方法,分别是: JavaScript代码 jQuery.fn.extend( ...
- JavaScript Array 对象扩展方法
/** 删除数组中指定索引的数据 **/ Array.prototype.deleteAt = function (index) { if (index < 0) { return this; ...
- JavaScript String 对象扩展方法
/** 在字符串末尾追加字符串 **/ String.prototype.append = function (str) { return this.concat(str); } /** 删除指定索引 ...
- 转译es6原生原生对象及方法,如Object.assign,Object.keys等,及promise
下面主要为兼容恶心的ie 1,首先引入‘babel-polyfill’,可写在webpack.dev.js的entry.vendors数组里面 2,在入口文件如app.js里面import 'babe ...
- js Array数组对象常见方法总结
Array对象一般用来存储数据. 其常用的方法包括: 1.concat()方法 concat() 方法用于合并两个或多个数组.它不会更改现有数组,而是返回一个新数组. 例如: var arr1=[1, ...
- 常用的js对象扩展方法
1. 字符串的replaceAll String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) { if (!R ...
- jquery扩展方法
jquery插件的开发包括两种:一种是类级别的插件开发,即给jquery添加新的全局函数,相当于给jquery类本身添加方法. jquery的全局函数就是属于jquery命名空间的函数,另一种是对象级 ...
随机推荐
- xcode 出现the file couldn't be opened 怎么解决
右键——show In finder——显示xcode包内容——将有数字的删除——把有用的xcode双击
- python实现简易数据库之二——单表查询和top N实现
上一篇中,介绍了我们的存储和索引建立过程,这篇将介绍SQL查询.单表查询和TOPN实现. 一.SQL解析 正规的sql解析是用语法分析器,但是我找了好久,只知道可以用YACC.BISON等,sqlit ...
- [原创]Net实现Excel导入导出到数据库(附源码)
关于数据库导出到Excel和SQLServer数据导出到Excel的例子,在博客园有很多的例子,自己根据网上搜集资料,自己做了亦歌简单的demo,现在分享出来供初学者学习交流使用. 一.数据库导入导出 ...
- PDA设备小知识--(IP)工业防护等级含义
IP(INTERNATIONAL PROTECTION)防护等级是专门的工业防护等级,,它将电器依其防尘.防湿气之特性加以分级.IP防护等级是由两个数字所组成,第1个数字表示电器离尘.防止外物侵入的等 ...
- angular的编辑器tinymce
angular的插件的确挺少的, 编辑器更是少, ui-tinymce是angular-ui推荐的一款编辑器(GIT: https://github.com/angular-ui/ui-tinymce ...
- Chrome的Crash Report服务
<本文转自:http://www.cppblog.com/woaidongmao/archive/2009/10/22/99211.aspx> 本文翻译自debugInfo网站上一篇文章g ...
- 并行程序设计模式--Master-Worker模式
简介 Master-Worker模式是常用的并行设计模式.它的核心思想是,系统有两个进程协议工作:Master进程和Worker进程.Master进程负责接收和分配任务,Worker进程负责处理子任务 ...
- word-break:brea-all;word-wrap:break-word的区别
//form==>http://www.cnblogs.com/2050/archive/2012/08/10/2632256.html <p style="background ...
- poj1308 并查集
比较恶心 1: 0 0 空树是一棵树 2: 1 1 0 0 不是树 3: 1 2 1 2 0 0 不是树... 4: 1 2 2 3 4 5 不是树 森林不算是树 5: 1 2 2 3 3 4 4 5 ...
- java.io.FileNotFoundException:文件名、目录名或卷标语法不正确
出现次错误的原因主要是在windows系统下创建文件需要遵循其文件名的规则.导致创建文件失败,从而提示filenotfound异常,文件未找到 Windows 中文件夹命名规则是: ① 文件名或文件夹 ...