Upload
cordelia-josephine-mosley
View
332
Download
0
Embed Size (px)
Citation preview
Function in JavaScript
Procedural Functions
◦几乎所有编程语言都有类似的写法◦大家对此都很习惯了◦hello 是一个函数的名字◦但如果 hello 也可以是一个变量的名字呢?
function hello(who) { alert('Hello '+who); // outputs "Hello world"}
hello('world');
Function in JavaScript
Functions As Variables
◦和之前的实际效果是几乎一样的◦多了个 var◦不仅仅是”语法糖”
var hello = function (who) { alert('Hello '+who); // outputs "Hello world"}
hello('world');
Function in JavaScript
Passing Functions To Functions
◦函数可以像数字、字符串、数组、 Object 一样当参数
var say = function(what) { what('say function');}
var hello = function (who) { alert('Hello '+who); // outputs "Hello say function"}
say(hello);
Function in JavaScript
Passing Functions To Functions (2)
function doSomething() { alert('you pushed my button!');}
document.onclick=doSomething;
function pushedMyButton() { alert('you pushed my button!');}function doSomething() { return pushedMyButton; // return a pointer to the pushedMyButton function}document.onclick=doSomething();
Function in JavaScript
Passing Functions To Functions (3)
var test = function () { return "This is a String";}
var testCopy = test; // testCopy is a pointer to the test function()var testStr = test(); // testStr contians "This is a string"var testing = testCopy(); // testing contains "This is a string"
Function in JavaScript
Anonymous Functions
◦我们没法再直接找到这个 function 并调用◦function 看起来更像是一个 value ,而不是传统的
function 了
document.onmousedown = function() { alert("You pressed the mouse button");
}
Function in JavaScript
Self-Invoking Functions
◦自调用的函数◦注意红色的部分,括号们◦该函数只存在到第一行结束
var x = (function () {return(5+6)})();document.writeln(typeof(x)+'<br/>');//Outputs: Numberdocument.writeln(x); //Outputs: 11;
Function in JavaScript
Self-Invoking Functions (2)
◦给页面增加一个 script 标签
( function () { var s=document.createElement("script"); s.src="http://mydomain.com/script.js"; document.body.appendChild(s); } ) ();
<A HREF='javascript:(function(){var s=document.createElement("script"); s.src="http://mydomain.com/script.js"; document.body.appendChild(s);})();'>My First Bookmarklete App</A>
Function in JavaScript
Understanding Function Scope◦function as variable◦<script> 标签下的 function,var 都是 global 的◦Javascript 变量的作用域是 function ,不是 block
看个例子,这一页放不下了……
Function in JavaScript
Understanding Function Scope (2)
◦如何解决? 将红色的 var 去掉即可◦为啥?因为没有 var 且没定义的变量,会自动被定义为
global 的
var globalFunction = function(){ // global, can be accessed anywhere. alert('hello world');}
var containerFunction = function(){ // global, can be accessed anywhere. var subFunction = function(){ // private--global to containerFunction and its children only. alert("I'm Private"); globalFunction(); // We can access global Function here 2 levels deep. } globalFunction(); // We can access global Function here 1 level deep. subFunction() // We can access subFunction inside containerFunction.}
containerFunction();subFunction(); // This produces an error because // subfunction() only exists inside containerFunction
Function in JavaScript
Understanding Function Scope (3)
输出:
var data = "Global";
function test(){ console.log(data); data = "inside test"; console.log(data);}
function test2(){ console.log(data); var data = "inside test2"; console.log(data);}test();test2();Console.log(data);
"Global";"inside test";undefined"inside test2";"inside test";
Function in JavaScript
Function Arguments◦定义:
◦调用
var myFunc = function(a,b,c) { console.log(a,b,c)
}
myFunc(1); //1,undefined,undefinedmyFunc(1,2); //1,2,undifinedmyFunc(1,2,3); //1,2,3myFunc(1,2,3,4,5,6,7,8,9,10);//1,2,3
Function in JavaScript
Function Arguments (2)function test(x){ console.log(this,arguments);}
>>> test(1)Window shiretoko [1]>>> test("a",[1,function(){alert("aaa")}],test)Window shiretoko ["a", 1,function () { alert("aaa"); }, test(x)]>>> test.apply({a:1,b:window},["a",[1,function(){alert("aaa")}],test])Object a=1 b=window ["a", 1,function () { alert("aaa"); }, test(x)]
Functional JavaScript
λ——Lambda http://osteele.com/sources/javascript/functional/
map('1+', [2, 3]) //[3, 4]map('x*x', [1,2,3,4]) //[1, 4, 9, 16]select('>2', [1,2,3,4]) //[3, 4]reduce('x*2+y', 0, [1,0,1,0]) //10map(guard('2*', not('%2')), [1,2,3,4])//[1, 4, 3, 8]
Functional JavaScript
String lambdas
Explicit parameters◦含有” ->” 的字符串
'x+1'.lambda()(2); //3'x+2*y'.lambda()(2, 3);//8var square = 'x*x'.lambda();//functionsquare(3);//9square(4);//16
'x y -> x+2*y'.lambda()(2, 3); //8'y x -> x+2*y'.lambda()(2, 3); //7// 如果有” _” ,则会当做 unary function ,且 _ 为参数的名字'_ -> _+1'.lambda()(2); //3‘_ -> _*_’.lambda()(3); //9 等价于 'x -> x*x'.lambda()( 3)
Functional JavaScript
Implicit parameters◦ 不指定任何变量,则是”隐式变量”◦ 以除掉” -” 之外的操作符或者关系式开头或者结尾,则对应的隐式参数
会自动添加至头 / 尾
◦ 字符串中的变量,按照出现顺序作为参数顺序
'*2'.lambda()(2); //4'/2'.lambda()(4);//2'2/'.lambda()(4);//0.5'/'.lambda()(2, 4);//0.5
'x+1'.lambda()(2);//3'x*x'.lambda()(3);//9'x + 2*y'.lambda()(1, 2);//5'y + 2*x'.lambda()(1, 2);//5
Functional JavaScript
Chaining◦用 -> 来做 chain
'x y -> x+y'.lambda()(2, 3);//5'x -> y -> x+y'.lambda()(2)(3);//5'x -> y -> x+y'.lambda()(2);//function()
Functional JavaScript
Higher-order functions◦ 名为“ Functional” 的“ namespace”◦ Functional.install() 将 Functional 里头的函数安装至 window
下,每次就可以直接调用” map” 等函数,不需要敲namespace 了
◦ map, select, reduce, some, every, etc…Functional.map(function(x){return x+1}, [1,2,3])//[2,3,4]Functional.map(‘_+1’, [1,2,3]); //[2,3,4]map('_.length', 'here are some words'.split(' '));//[4, 3, 4, 5]select('>2', [1,2,3,4]);//[3, 4]reduce('2*x+y', 0, [1,0,1,0]);//10some('>2', [1,2,3,4]);//trueevery('>2', [1,2,3,4]);//false
Functional JavaScript
Higher-order functions (2)◦ compose, sequence◦ Functional.install() 将 Functional 里头的函数安装至 window
下,每次就可以直接调用” map” 等函数,不需要敲namespace 了compose('+1', '*2')(1); //3
sequence('+1', '*2')(1); //4compose('+1', '*2', '_.length')('a string'); //17compose.apply(null, map('x -> y -> x*y+1', [2,3,4]))(1); //33
Functional JavaScript
Higher-order functions (3)◦更多的内容:
foldr, pluck, invoke, until, guard, curry, ncurry, rncurry, partial
Function in Javascript
JavaScript 1.6-1.8◦ every() - runs a function on items in the array while that function is returning
true. It returns true if the function returns true for every item it could visit. ◦ filter() - runs a function on every item in the array and returns an array of all
items for which the function returns true. ◦ forEach() - runs a function on every item in the array. ◦ map() - runs a function on every item in the array and returns the results in an
array. ◦ some() - runs a function on items in the array while that function returns false. It
returns true if the function returns true for any item it could visit. ◦ reduce() - runs a function on every item in the array and collects the results from
previous calls.◦ reduceRight() - runs a function on every item in the array and collects the results
from previous calls, but in reverse. References
◦ https://developer.mozilla.org/en/New_in_JavaScript_1.6◦ https://developer.mozilla.org/en/New_in_JavaScript_1.8◦ https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Arrays