javascript笔记--函数

Three ways to create a function:

1.Declarative function: parsed when the javascript application is first loaded.(can place anywhere)

2.Anonymous function or function constructor:parsed each time it's accessed.

3.Function literal or function expression:used in place-such as a callback function.Aslo parsed once

when the javascript application is loaded.can also anonymous.(Place before the function is used)

 

function factorial(n) {
console.log(n);
return n==1 ? 1 : n * factorial(n -1);
}

function noBlock(n, callback){
setTimeout(function() {
var val = factorial(n);
if (callback && typeof callback == "function") {
callback(val);
}
},0);
}

console.log("Top of the morning to you");

noBlock(3, function(n) {
console.log("first call ends with " + n);
noBlock(n, function(m) {
console.log("final result is " + m);
});
});

var tst = 0;
for (i=0; i<10; i++) {
tst+=i;
}

console.log("value of tst is " + tst);

noBlock(4, function(n) {
console.log("end result is " +n);
});
console.log("not doing too much");

 

1.Create a funtion that can remember data, but without having to use global variables and without resending the same data

with each function call.

A way to persist this data from one function to another is to create one of the functions within the other, so both have access  to the data,and then return the inner function from the outer.

when the returned function is using the outer function's scope, is known as a

function closure.

function outer (x) {

  return function(y) {return x * y;};

}

var multiThree = outer(3);

alert(multiThree(2)); alert(multiThree(3));

 

2. Converting function argument into an array

use Array.prototype.slice() and then the function call() method to convert arguments 

collection into an array. 

an array-like object consisting of all arguments passed to the function

convert a NodeList into an array

function sumRounds() {
var args = [].slice.call(arguments);

return args.reduce(function(val1, val2) {
return parseInt(val1, 10) + parseInt(val2, 10);
});
}

var sum = sumRounds("2.3", 4, 5, "16", 18.1);

3.Reducing redundancy by using a partial application

One function perform a process on a given number of arguments and return a

result, while a second function acts as a function factory:churning out functions thet

return the first function, but with arguments already encoded.
function makeString(ldelim, str, rdelim) {
return ldelim + str + rdelim;
}

function quoteString(str) {
return makeString("'", str, "'");
}

function barString(str) {
return makeString("-", str, "-");
}

console.log(quoteString("apple"));
console.log(barString("apple"));

 

console.log(sum);

posted @ 2015-12-18 09:49  sky.zhao  阅读(141)  评论(0编辑  收藏  举报