javascript函数作为变量传递

js中当函数不加括号时可以把函数当成值传递。

无参数:

1
2
3
4
5
6
// 无参函数
function foo (){
console.log(1);
}

var bar = foo;

有参时需要用一个匿名函数:

1
2
3
4
5
6
function foo (arg1, arg2) {
console.log(1);
}
var bar = function(arg1, arg2) {
foo(arg1, arg2);
};

javascript中的隐式类型转换

在Javascript 中,只有在一些极少数情况下才会因为类型错误而抛出一个异常,大多数情况会偷偷的把类型转换了,这就是所谓的“隐式类型转换”,js中的基本类型有:string、number、boolean、object、symbol、undefined、null,其中object为引用类型。不同类型的变量比较或运算时会产生隐式类型转换。

算术运算

+号可以当算术运算符也能当连字符号,使用+情况为:

1
2
3
4
5
6
7
// 只要有一个类型为string,另一个也会转为string
console.log(1+'1') // '11'
console.log('1'+1) // '11'
console.log('1'+true) // '11'
// number和boolean时,boolean转为number
console.log(1+true) // '2'

javascript中创建对象的几种方式

javascript中没有类,可以用一些变通的方法模拟出来,整理的几种创建类的方法。

工厂方式

缺点是不能实现私有属性和私有方法

1
2
3
4
5
6
7
8
9
10
11
function Person() {
var Obj = new Object();
Obj.name = 'attr name';
Obj.eat = function() {
console.log('method eat');
}
return Obj;
}
var person = Person();
console.log(person.name);
console.log(person.eat());

把github作为静态资源cdn

博客是用hexo搭建的,没有上传图片的功能,于是想把图片都放github上。需要图片的时候![Alt text](/path/to/img.jpg "Optional title")这样就可以插入了。

在github上创建仓库,名字自己取,以我自己的为例,仓库为static_cdn,克隆到本地:

1
2
3
4
5
6
7
# 克隆
$ git clone git@github.com:liukaijv/static_cdn.git
# 打开目录
$ cd static_cdn
# 新建images文件夹
$ mikdir images

让jquery插件支持AMD和CMD规范

jquery插件支持AMD和CMD规范的改造:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
;function(root, factory) {
"use strict";
if (typeof define === 'function' && (define.amd || define.cmd)) {

// register as anon module
define(['jquery'], factory);

} else {

// invoke directly
factory( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto );

}
}(this, function($){
'use strict';

// your code

});

hexo的md文件中使用html、css、javascript

有时候想写点前端小demo,因为代码量实在是太少了,几行css、几行javascript;不想放在codepen作为引用,也不想单独做一个页面放到主题的source文件夹下,于是就有了在md文件里直接写的想法。

Apache的访问权限配置

在apache2.4版本之前做客户端访问控制,是用Allow Deny Order指令做访问控制的,而在2.4的版本上是用的用法跟之前的版本大不相同,如下

################################################ 
2.2上的配置 
Order deny,allow 
Deny from all 
 
2.4上的配置 
Require all denied 
 
################################################ 
2.2上的配置 
Order allow,deny 
Allow from all 
 
2.4上的配置 
Require all granted 
 
################################################# 

js验证只能输入数字

js验证只能输入数字函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function parseNumber(value) {
// 替换非数字值
value = value.replace(/[^\d.]/g, '');
// 替换第一位为.
value = value.replace(/^\./g, '');
// 替换最后一位为.
value = value.replace(/\.$/g, '');
// 替换连续.+
value = value.replace(/\.{2,}/g, '.');
// .号前只能有一个0
value = value.replace(/^0+\./g, '0.');
// 保留一个.,替换其它的.
value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
return value;
}

javascript获取浏览器视口大小

1
2
3
4
5
6
7
8
9
10
11
12
13
function getViewport() {
if(document.compatMode == 'BackCompat'){
return {
width: document.body.clientWitdh,
height: document.body.clientHeight
}
} else {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
}
}
}