持续积累中~

拓展原型

Function.prototype.method = function(name, extend) {
if(!this.prototype[name]) {
this.prototype[name] = extend;
}
return this;
}

实现继承·方法1

Function.method("inherits", function(Parent) {
var _proptotype = Object.create(Parent.prototype);
_proptotype.constructor = this.prototype.constructor;
this.prototype = _proptotype;
return this;
})

实现继承·方法2

function inherits(child, parent) {
var _proptotype = Object.create(parent.prototype);
_proptotype.constructor = child.prototype.constructor;
child.prototype = _proptotype;
return {
"child": child,
"parent": parent
};
}

实现继承·方法3

//只创建临时构造函数一次
var inherit = (function () {
var F = function () {};
return function (C, P) {
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype; // 存储超类
C.prototype.constructor = C; // 重置构造函数指针
}
})();

浅拷贝

function simpleCopy() {
var c = {};
for(var i in p) {
c[i] = p[i];
}
return c;
}

深拷贝

function deepCopy(p, c) {
var c = c || {};
for(var i in p) {
if(typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}

带特性值的浅拷贝

function Composition(target, source){
var desc = Object.getOwnPropertyDescriptor;
var prop = Object.getOwnPropertyNames;
var def_prop=Object.defineProperty;
prop(source).forEach(function(key) {
def_prop(target, key, desc(source, key))
})
return target;
}

mixin混合

function mix() {
var arg, prop, child = {};
for(arg = 0; arg < arguments.length; arg += 1) {
for(prop in arguments[arg]) {
if(arguments[arg].hasOwnProperty(prop)) {
child[prop] = arguments[arg][prop];
}
}
}
return child;
}

对象拓展

var MYAPP = MYAPP || {};
MYAPP.namespace = function(ns_string) {
var parts = ns_string.split('.'),
parent = MYAPP,
i;
//忽略第一个
if(parts[0] === "MYAPP") {
parts = parts.slice(1);
}
for(i = 0; i < parts.length; i += 1) {
//如果属性不存在,就创建
if(typeof parent[parts[i]] === "undefined") {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
};
MYAPP.namespace('once.upon.a.time.there.was.this.long.nested.property');

函数柯里化(Currying)

function curry(fn){
var args = Array.prototype.slice.call(arguments, 1);
return function(){
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return fn.apply(null, finalArgs);
};
}
function add(num1, num2){
return num1 + num2;
}
var curriedAdd = curry(add, 5);
alert(curriedAdd(3)); //8

函数节流

function throttle(fn, wait){
var timer;
return function(...args){
if(!timer){
timer = setTimeout(()=>timer=null, wait);
return fn.apply(this, args);
}
}
}

函数防抖

function debounce(fn, delay){
var timer = null;
return function(...args){
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
}
}

跨文件共享私有对象(模块互访)

var blogModule = (function(my) {
var _private = my._private = my._private || {},
_seal = my._seal = my._seal || function() {
delete my._private;
delete my._seal;
delete my._unseal;
},
_unseal = my._unseal = my._unseal || function() {
my._private = _private;
my._seal = _seal;
my._unseal = _unseal;
};
return my;
}(obj || {}));

类型判断

function isType(val, type) {
val = Object.prototype.toString.call(val).toLowerCase();
if(typeof(type) === "string") {
return val === '[object ' + type.toLowerCase() + ']';
}
return val.replace(/(\[object\s)|(\])/g, "");
}

软绑定[默认绑定可设置]

    Function.prototype.softBind = function(obj) {
var fn = this;
// 捕获所有 curried 参数
var curried = [].slice.call( arguments, 1 );
var bound = function() {
return fn.apply(
(!this || this === (window || global)) ?
obj : this
curried.concat.apply( curried, arguments )
);
};
bound.prototype = Object.create( fn.prototype );
return bound;
};

将时间戳转换成时间描述

function getTimeDesc(time) {
var
_n = 12 * 30 * 24 * 60 * 60 * 1000,
_y = 30 * 24 * 60 * 60 * 1000,
_d = 24 * 60 * 60 * 1000,
_h = 60 * 60 * 1000,
_m = 60 * 1000,
_s = 1000,
n, y, d, h, m, s, value; n = parseInt(time > _n ? time / _n : 0);
n = n ? (n + '年') : '';
time = time % _n; y = parseInt(time > _y ? time / _y : 0);
y = y ? (y + '月') : '';
time = time % _y; d = parseInt(time > _d ? time / _d : 0);
d = d ? (d + '天') : '';
time = time % _d; h = parseInt(time > _h ? time / _h : 0);
h = h ? (h + '时') : '';
time = time % _h; m = parseInt(time > _m ? time / _m : 0);
m = m ? (m + '分') : '';
time = time % _m; s = parseInt(time > _s ? time / _s : 0);
s = s + '秒'; value = n + y + d + h + m + s;
console.log(value);
return value;
}

toFixed精度修复

  Number.prototype.toFixed = function (n) {
if (n > 20 || n < 0) {
throw new RangeError('toFixed() digits argument must be between 0 and 20');
}
const number = this;
if (isNaN(number) || number >= Math.pow(10, 21)) {
return number.toString();
}
if (typeof (n) == 'undefined' || n == 0) {
return (Math.round(number)).toString();
} let result = number.toString();
const arr = result.split('.'); // 整数的情况
if (arr.length < 2) {
result += '.';
for (let i = 0; i < n; i += 1) {
result += '0';
}
return result;
} const integer = arr[0];
const decimal = arr[1];
if (decimal.length == n) {
return result;
}
if (decimal.length < n) {
for (let i = 0; i < n - decimal.length; i += 1) {
result += '0';
}
return result;
}
result = integer + '.' + decimal.substr(0, n);
const last = decimal.substr(n, 1); // 四舍五入,转换为整数再处理,避免浮点数精度的损失
if (parseInt(last, 10) >= 5) {
const x = Math.pow(10, n);
result = (Math.round((parseFloat(result) * x)) + 1) / x;
result = result.toFixed(n);
} return result;
};

js精度运算

var floatObj = function() {

    // 判断obj是否为一个整数
function isInteger(obj) {
return Math.floor(obj) === obj
} /*
* 将一个浮点数转成整数,返回整数和倍数。如 3.14 >> 314,倍数是 100
* @param floatNum {number} 小数
* @return {object}
* {times:100, num: 314}
*/
function toInteger(floatNum) {
var ret = {times: 1, num: 0}
var isNegative = floatNum < 0
if (isInteger(floatNum)) {
ret.num = floatNum
return ret
}
var strfi = floatNum + ''
var dotPos = strfi.indexOf('.')
var len = strfi.substr(dotPos+1).length
var times = Math.pow(10, len)
var intNum = parseInt(Math.abs(floatNum) * times + 0.5, 10)
ret.times = times
if (isNegative) {
intNum = -intNum
}
ret.num = intNum
return ret
} /*
* 核心方法,实现加减乘除运算,确保不丢失精度
* 思路:把小数放大为整数(乘),进行算术运算,再缩小为小数(除)
*
* @param a {number} 运算数1
* @param b {number} 运算数2
* @param digits {number} 精度,保留的小数点数,比如 2, 即保留为两位小数
* @param op {string} 运算类型,有加减乘除(add/subtract/multiply/divide)
*
*/
function operation(a, b, digits, op) {
var o1 = toInteger(a)
var o2 = toInteger(b)
var n1 = o1.num
var n2 = o2.num
var t1 = o1.times
var t2 = o2.times
var max = t1 > t2 ? t1 : t2
var result = null
switch (op) {
case 'add':
if (t1 === t2) {
// 两个小数位数相同
result = n1 + n2
} else if (t1 > t2) {
// o1 小数位 大于 o2
result = n1 + n2 * (t1 / t2)
} else {
// o1 小数位 小于 o2
result = n1 * (t2 / t1) + n2
}
return (result / max).toFixed(digits);
case 'subtract':
if (t1 === t2) {
result = n1 - n2
} else if (t1 > t2) {
result = n1 - n2 * (t1 / t2)
} else {
result = n1 * (t2 / t1) - n2
}
return (result / max).toFixed(digits);
case 'multiply':
result = (n1 * n2) / (t1 * t2)
return result.toFixed(digits);
case 'divide':
result = (n1 / n2) * (t2 / t1)
return result.toFixed(digits);
}
} // 加
function add(a, b, digits) {
let value = operation(a, b, digits, "add");
return value == NaN || value == Infinity ? 0 : value;
}
// 减
function subtract(a, b, digits) {
let value = operation(a, b, digits, "subtract");
return value == NaN || value == Infinity ? 0 : value;
}
// 乘
function multiply(a, b, digits) {
let value = operation(a, b, digits, "multiply");
return value == NaN || value == Infinity ? 0 : value;
}
// 除
function divide(a, b, digits) {
let value = operation(a, b, digits, "divide");
return value == NaN || value == Infinity ? 0 : value;
} return { add, subtract, multiply, divide };
}();

js滚轮绑定

EventTarget.prototype.onMousewheel = function (fn, capture) {
    if (document.mozFullScreen !== undefined) {
        type = "DOMMouseScroll";
    } else {
        type = "mousewheel";
    }
    this.addEventListener(type, function (event) {
        event.delta = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
        fn.call(this, event);
    }, capture || false);
}

js点击下载

function browserDownload (url) {
  var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
save_link.href = url;
save_link.download = name;
var ev = document.createEvent("MouseEvents");
ev.initMouseEvent(
"click",
true,
false,
window,
0,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null
);
save_link.dispatchEvent(ev);
}

javascript实用代码片段的更多相关文章

  1. Javascript实用代码片段(译)

    原文:http://www.bestdesigntuts.com/10-time-saving-javascript-code-snippets-for-web-developers 1. 同高或同宽 ...

  2. 100个直接可以拿来用的JavaScript实用功能代码片段(转载)

    把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 目录如下: 1.原生JavaScript实现字符串长度截取2.原生JavaS ...

  3. JavaScript实用功能代码片段

    把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 1.原生JavaScript实现字符串长度截取 function cutst ...

  4. 100个直接可以拿来用的JavaScript实用功能代码片段(转)

    把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 目录如下: 1.原生JavaScript实现字符串长度截取2.原生JavaS ...

  5. 回归 | js实用代码片段的封装与总结(持续更新中...)

      上一次更博还是去年10月28号了,截至今天已经有整整4个月没有更新博客了,没更新博客不是代表不学了,期间我已经用vue做了两个项目,微信小程序做了一个项目,只是毕竟找到工作了,想偷偷懒,你懂的. ...

  6. PHP实用代码片段(三)

    1. 目录清单 使用下面的 PHP 代码片段可以在一个目录中列出所有文件和文件夹. function list_files($dir) { if(is_dir($dir)) { if($handle ...

  7. PHP实用代码片段(二)

    1. 转换 URL:从字符串变成超链接 如果你正在开发论坛,博客或者是一个常规的表单提交,很多时候都要用户访问一个网站.使用这个函数,URL 字符串就可以自动的转换为超链接. function mak ...

  8. C#程序员经常用到的10个实用代码片段 - 操作系统

    原文地址  如果你是一个C#程序员,那么本文介绍的10个C#常用代码片段一定会给你带来帮助,从底层的资源操作,到上层的UI应用,这些代码也许能给你的开发节省不少时间.以下是原文: 1 读取操作系统和C ...

  9. 几个有用的JavaScript/jQuery代码片段(转)

    1. 检查数据是否包含在Array中 //jQuery实现 jQuery.inArray("value", arr); // 使用方法: if( jQuery.inArray(&q ...

随机推荐

  1. Python-基于向量机SVM的文本分类

    项目代码见 Github: 1.算法介绍 2.代码所用数据 详情参见http://qwone.com/~jason/20Newsgroups/ 文件结构 ├─doc_classification.py ...

  2. SpringBoot集成Spring Security入门体验

    一.前言 Spring Security 和 Apache Shiro 都是安全框架,为Java应用程序提供身份认证和授权. 二者区别 Spring Security:重量级安全框架 Apache S ...

  3. Maven 梳理-安装配置

    项目构建过程包括[清理项目]→[编译项目]→[测试项目]→[生成测试报告]→[打包项目]→[部署项目]这几个步骤,这六个步骤就是一个项目的完整构建过程. 下载后解压   配置环境变量 F:\jtDev ...

  4. FormatMessage将错误代码转换成对应的字符串

    // ConsoleApplication1.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" int _tmain(int argc, _T ...

  5. springboot 2.1.3.RELEASE版本解析.properties文件配置

    1.有时为了管理一些特定的配置文件,会考虑单独放在一个配置文件中,如redis.properties: #Matser的ip地址 redis.host=192.168.5.234 #端口号 redis ...

  6. 阿里云服务器CentOS6.9安装Tomcat

    上篇讲了CentOS6.9安装jdk,这篇来讲Tomcat的安装,本来准备使用yum命令安装的,但是通过 yum search tomcat 发现只有tomcat6,所以就在官网下了一个tomcat8 ...

  7. python 列表,集合,字典,字符串的使用

    PY PY基础 append 在末尾添加元素 pop 删除末尾元素 insert(i,item)在i位插入元素 pop(i)删除i位元素 只有1个元素的tuple定义时必须加一个逗号,,来消除歧义 i ...

  8. linux 装composer的出现的问题

    curl -sS https://getcomposer.org/installer | php php 值得是php的liux下的安装目录 php环境变量 当装compser 的时候,出现      ...

  9. aircrack-ng wifi密码破解

    wifi密码破解 步骤1:查看网卡信息 ifconfig 找到你要用到的网卡 步骤2:启动网卡监听模式 airmon-ng start wlan0 我的是wlp2s0 步骤三:查看网卡变化 wlan0 ...

  10. 求n以内的质数(质数的定义:在大于1的自然数中,除了1和它本身意外,无法被其他自然数整除的数)

    思路: 1.(质数筛选定理)n不能够被不大于根号n的任何质数整除,则n是一个质数2.除了2的偶数都不是质数代码如下: /** * 求n内的质数 * @param int $n * @return ar ...