arguments
is an array-like object containing all of the arguments passed
into the function.
arguments
has a property named callee
,
which is a pointer to the function that owns the arguments
object.
function factorial(num){// w ww .j a v a 2 s.c o m
if (num <= 1) {
return 1;
} else {
return num * arguments.callee(num-1)
}
}
var trueFactorial = factorial;
factorial = function(){
return 2;
};
console.log(trueFactorial(5));
console.log(factorial(5));
The code above generates the following result.
this
is a reference to the function context object.
When a function is called in the global scope of a web page, this
points
to window.
<!--from w w w. j av a 2 s .co m-->
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.myName = "XML";
function printMyName(){
console.log(this.myName);
}
printMyName(); //"XML"
var o = { myName: "HTML" };
o.printMyNameForMyObject = printMyName;
o.printMyNameForMyObject(); //"HTML"
</script>
</head>
<body>
</body>
</html>
printMyName() is defined globally and references the this
object.
this
is not determined until the function is called.
When printMyName() is called in the global scope, it outputs "XML" because this is pointing to window, which means this.myName evaluates to window.myName.
By assigning the function to the object o and then calling o.printMyName(), the this object points to o, so this.myName evaluates to o.myName and "HTML" is displayed.
caller
is a reference to the function that called this function or null if the function was
called from the global scope.
function outer(){ inner(); } function inner(){ console.log(inner.caller); } outer();
Because outer() calls inner(), inner.caller points back to outer().
In strict mode, arguments.callee and arguments.caller are not supported.
You can even call arguments.callee.caller:
function outer(){
inner();
}
function inner(){
console.log(arguments.callee.caller);
}
outer();
The code above generates the following result.
The length
property indicates the number of named arguments that the function expects.
function myFunction1(name){//from w w w .j a va 2s .co m
console.log(name);
}
function myFunction2(num1, num2){
return num1 + num2;
}
function myFunction3(){
console.log("hi");
}
console.log(myFunction1.length); //1
console.log(myFunction2.length); //2
console.log(myFunction3.length); //0
The code above generates the following result.