MENU
Function Object
A function object is evaluated each time it is used, which is less efficient than calling pre-compiled function declarations.
Properties: length returns the number of parameters expected by a function. Within any function body, you can use the arguments arrayto access the parameters.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function S(){
var sum=0;
for (i=0; i<arguments.length; i++){
sum+=arguments[i];
}
console.log(arguments.callee); // shows the function definition
return sum;}console.log(S(10,20,30)); // … 60console.log((function(a,b,c){}).length); // 3
</script></body><html>
Methods: call( o1[,o2......] ) calls the function by passing o1 as the 'this' value, and subsequent arguments as the parameters. apply(o[,arr]) is similar to call() but passes the arguments as an array instead.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var animals = [ { species: 'Lion', name: 'King' },
{ species: 'Whale', name: 'Willy' }];for (let i = 0; i < animals.length; i++) {
(function(i) {
console.log('#' + i + ' ' + this.species + ': ' +
this.name);
}).call(animals[i], i);}// #0 Lion: King// #1 Whale: Willy
</script></body><html>
bind(o1[,o2......]) returns a new function by passing o1 as the 'this' value, and subsequent arguments as the parameters.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function sum(){
var sum=0;
for (i=0; i<arguments.length; i++){
sum+=arguments[i];
}
return sum;}console.log(sum(10,20,30)); // 60plus1000 = sum.bind(null,1000);console.log(plus1000(10,20,30)); // 1060
</script></body><html>
toString() returns a string representation of the function.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function sum(a,b){return a+b;}console.log(sum.toString());// function sum(a,b){return a+b;}
</script></body><html>
Below are two ways to execute a string of JavaScript code:
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var code = "console.log(100);"var f = Function(code); f(); // 100eval(code); // 100
</script></body><html>