函数
函数的定义
function test(a, b) {
var sun = a + b;
document.write(sun);
return sun;
}
function test() {
document.write("function test");
return undefined;
}
test();
test(1, 2);
默认参数的实现
// 通过逻辑或实现
function test(x, y) {
x = x || 0
y = y || 0
return x + y
}
// 通过 if 判断实现
function test2(x, y) {
if (x === undefined) {
x = 0
}
if (y === undefined) {
y = 0
}
return x + y
}
// 通过 arguments 实现
function test3(x, y) {
x = arguments[0] ? arguments[0] : 0
y = arguments[1] ? arguments[1] : 0
return x + y
}
可变参数的实现
// 通过 arguments 实现可变参数
function test4() {
var argSize = arguments.length
var sum = 0
for (var i = 0
sum = sum + arguments[i]
}
return sum
}
document.write(test4(1,2,3,4,5))
变量作用域
var x = 1;
function test5() {
var y = 2;
z = 3;
alert(x);
alert(y);
alert(z);
}
test5();
alert(x);
alert(z);
全局函数-数值型函数
document.write(parseInt("66"));
document.write("<br />");
document.write(parseFloat("6.6"));
document.write("<br />");
document.write(isFinite(66));
document.write("<br />");
document.write(isNaN(66));
document.write("<br />");
全局函数-常用全局函数
var url = "http://www.baidu.com?search= 6 6 6";
var res = encodeURI(url);
document.write(res);
document.write("<br />");
document.write(decodeURI(res))
document.write("<br />");
var res2 = encodeURIComponent(url);
document.write(res2);
document.write("<br />");
document.write(decodeURIComponent(res2));
document.write("<br />");
var res3 = escape(url);
document.write(res3);
document.write("<br />");
document.write(unescape(res3));
document.write("<br />");
eval("var val = 666");
document.write(val);
document.write("<br />");
var boo = Boolean(666);
document.write(boo);
document.write("<br />");
document.write(Number(boo));
document.write("<br />");
document.write(String(boo));
document.write("<br />");
匿名函数的应用
var testfunc = function(x,y){
return x + y;
}
document.write(testfunc(5,5));
document.write("<br />");
回调函数
function func1(x, y) {
return x() + y();
}
function func2() {
return 5;
}
function func3() {
return 5;
}
document.write(func1(func2,func3));
document.write("<br />");
function func(x, y) {
return x * y;
}
document.write(func.call(func, 5, 5));
document.write("<br />");
var params = [6, 6];
document.write(func.apply(func, params));
document.write("<br />");
自调函数
(
function() {
document.write("self call function");
}
)();
(
function(x, y) {
var sum = x + y;
document.write("value = " + sum);
}
)(6, 6);
内部私有函数
function test(t1) {
var test2 = function(t2) {
return t2 * 2;
}
return test2(t1);
}
document.write(test(8));
返回函数的函数
function show() {
alert("show");
return function() {
alert("JavaScript");
}
}
var showInfo = show();
showInfo();
重写自己的函数
function doSomething() {
alert("doSomething");
doSomething = function() {
alert("function");
}
}
doSomething();
doSomething();
函数构造器
var myFunc1 = function(a, b) {
return a + b;
}
var myFunc2 = new Function('a', 'b', 'return a + b');