Java script that makes your web site to come alive!
Allows client-side scripts to
1. Interact with the user
2. Control the browser
3. Communicate asynchronously
4. Alter the document content that is displayed
JavaScript copies many names and naming conventions from Java, but the two languages are otherwise unrelated and have very different semantics.
2 ways of writing a function
Examples:
1. Simple
1.1 recursive function
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
2. Anonymous
2.1 Immediately-invoked function expressions:
Allow functions to pass around variables under their own closures.
var v;
v = 1;
var getValue = (function(v) {
return function() {return v;};
})(v);
v = 2;
getValue(); // 1
2.2 closure example:
var displayClosure = function() {
var count = 0;
return function () {
return ++count;
};
}
var inc = displayClosure();
inc(); // returns 1
inc(); // returns 2
inc(); // returns 3
2.3 Variadic function
var sum = function() {
var i, x = 0;
for (i = 0; i < arguments.length; ++i) {
x += arguments[i];
}
return x;
}
sum(1, 2, 3); // returns 6
No comments:
Post a Comment