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命名空间的函数,另一种是对象级 ...
随机推荐
- [CareerCup] 11.2 Sort Anagrams Array 异位词数组排序
11.2 Write a method to sort an array of strings so that all the anagrams are next to each other. 这道题 ...
- JavaScript原型链和instanceof运算符的暧昧关系
时间回到两个月前,简单地理了理原型链.prototype以及__proto__之间的乱七八糟的关系,同时也简单了解了下typeof和instanceof两个运算符,但是,anyway,试试以下两题: ...
- 学习笔记:Twitter核心数据类库团队的Hadoop优化经验
一.来源 Streaming Hadoop Performance Optimization at Scale, Lessons Learned at Twitter (Data platform @ ...
- 如何优雅的写一篇安利文-以Sugar ORM为例
前言 我最近喜欢把写的十分优美的技术文章叫做安利文.首先,文章必须是原创而非软广:其次,阅读之后不仅能快速吸纳技术要点并入门开发,还能感同身受的体会作者热情洋溢的赞美和急于分享心得体验的心情,让人感觉 ...
- 每天一个linux命令(32):wc命令
Linux系统中的wc(Word Count)命令的功能为统计指定文件中的字节数.字数.行数,并将统计结果显示输出. 1.命令格式: wc [选项]文件... 2.命令功能: 统计指定文件中的字节数. ...
- chromium获取代码和编译
转自360公司的一位仁兄,链接地址:http://blog.gclxry.com/?p=364 之前一直是用一个chromium27的代码来研究chromium的代码.自己也调用chromium co ...
- “耐撕”团队 2016.03.24 站立会议
时间: 2016.03.22 17:00-17:30 18:30-19:00 成员: Z 郑蕊 * 组长 (博客:http://www.cnblogs.com/zhengrui0452/), ...
- java和linux的编码
最近要使用中科院计算所的关键词工具NLPIR,用java调用,在windows下测试后放到linux下跑,就发现会有乱码. windows下默认是GBK,linux下是utf-8,因此在意料之中(尽管 ...
- inline-block 和 float 的区别
1.float元素会自动成为一个块元素. 2.float元素,会脱离文档流! 默认脱离文档流的元素的z-index值是比没有脱离文档流的元素高的! 3.float:没有上下哦, 上下用margi ...
- 大概了解了flexbox
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...