Parameters
A function may not require any parameters, but if it does and you forget to pass them, JavaScript will assign the value undefined to the ones you skipped
If you pass more parameters than the function expects, the extra parameters will be silently ignored
You can create functions that are flexible about the number of parameters they accept. This is possible thanks to the arguments array that is created automatically inside each function
expression arguments.length returns the number of parameters passed when the function was called
Pre-defined Functions
a number of functions that are built into the JavaScript engine
parseInt()
takes any type of input (most often a string) and tries to make an integer
an optional second parameter, which is the radix, telling the function what type of number to expect decimal, hexadecimal, binary. Default is decimal, hex if 0x, and Oct if 0 is the prefix of the passed in value
If it fails, it returns NaN
>>> parseInt('123')
123
>>> parseInt('abc123')
NaN
>>> parseInt('FF', 10)
NaN
>>> parseInt('FF', 16)
255
parseFloat()
>>> parseFloat('123')
123
>>> parseFloat('123e-2')
1.23
>>> parseFloat('123e2')
12300
isNaN()
check if an input value is a valid number that can safely be used in arithmetic operations
>>> isNaN(NaN)
true
>>> isNaN(123)
false
isFinite()
checks whether the input is a number that is neither Infinity nor NaN.
>>> isFinite(Infinity)
false
>>> isFinite(-Infinity)
false
>>> isFinite(12)
true
Encode/Decode URIs
In a URL (Uniform Resource Locator) or a URI (Uniform Resource Identifier), some characters have special meanings
If you want to "escape" those characters, you can use the functions
- encodeURI()
- encodeURIComponent().
- assumes you're only passing a part of the URL, like a query string for example, and will encode all applicable characters
>>> var url = 'http://www.packtpub.com/scr ipt.php?q=this and that';
>>> encodeURI(url);
"http://www.packtpub.com/scr%20ipt.php?q=this%20and%20that"
The opposites of encodeURI() and encodeURIComponent() are decodeURI() and decodeURIComponent() respectively
eval()
eval() takes a string input and executes it as JavaScript code
So eval('var ii = 2;') is the same as simply var ii = 2;
The drawbacks of using eval() are
Performance—it is slower to evaluate "live" code, than to have the code directly in the script.
Security—JavaScript is powerful, which also means it can cause damage. If you don't trust the source of the input you pass to eval(), just don't use it.
alert()
it blocks the browser thread, meaning that no other code will be executed until the user closes the alert
Functions are Data
functions in JavaScript are actually data
function f()
{
return 1;
}
var f = function(){return 1;}
>>> function f(){return 1;}
>>> typeof f
"function"
it can be copied to a different variable and even deleted
>>> var sum = function(a, b) {return a + b;}
>>> var add = sum;
>>> delete sum
Anonymous Functions
functions can be used without assigning a name
You can pass an anonymous function as a parameter to another function
You can define an anonymous function and execute it right away
Callback Functions
function invoke_and_add(a, b) {
return a() + b();
}
function one() {
return 1;
}
function two() {
return 2;
>>> invoke_and_add(one, two);
>>> invoke_and_add(function(){return 1;}, function(){return 2;})
- They let you pass functions without the need to name them (which means there are less global variables)
- You can delegate the responsibility of calling a function to another function
- They can help with performance
When you pass a function A to another function B and B executes A, it's often said that A is a callback function
Self-invoking Functions
(function() {
alert('boo');
})()
(function(name) {
alert('Hello ' + name + '!');
})('dude')
One good reason for using self-invoking anonymous functions is to have some work done without creating global variables.
A drawback, of course, is that you cannot execute the same function twice.
This makes the anonymous self-invoking functions best suited for one-off or initialization tasks
Inner (Private) Functions
function a(param) {
function b(theinput) {
return theinput * 2;
}
;
return 'The result is ' + b(param);
};
Benefits:
You keep the global namespace clean (smaller chance of naming collisions).
Privacy—you expose only the functions you decide to the "outside world", keeping to yourself functionality that is not meant to be consumed by the rest of the application.
Functions that Return Functions
function a() {
alert('A!');
return function() {
alert('B!');
};
}
>>> var newFunc = a();
>>> newFunc();
To execute the returned function immediately
>>> a()();
Function, Rewrite Thyself!
>>> a = a(); alerts A!
>>> a() alerts B!
Function overwriting itself from the inside
function a() {
alert('A!');
a = function() {
alert('B!');
};
}
Example
var a = function() {
function someSetup() {
var setup = 'done';
}
function actualWork() {
alert('Worky-worky');
}
someSetup();
return actualWork;
}();
a self-invoking function—calls itself using the parentheses following its definition
The function executes for the first time, calls someSetup() and then returns a reference to the variable actualWork which is assigned to a
No comments:
Post a Comment