Analysis of the difference between callee and caller in javascript
- 2020-06-01 08:10:24
- OfStack
callee
callee is a property of an object, which is a pointer to a function of the parameter arguments object
First, let's write a function of order:
function chen(x){
if (x<=1) {
return 1;
} else{
return x*chen(x-1);
};
};
As you can see from this function, you're using recursive functions, and if you change the name of a function, you're going to have to change the name of the function inside, which is very inconvenient, so let's try callee
function chen(x){
if (x<=1) {return 1;
}else{
return x*arguments.callee(x-1);
};
};
According to the definition of callee, it can be seen that callee is a property of arguments object, which refers to the function of arguments object. This function is chen (chen= arguments.callee).
caller
caller is a property of a function object that holds a reference to the function that called the current function (pointing to the immediate parent of the current function)
Let me give you an example
function a(){
b();
};
function b(){
alert(b.caller);
};
a(); // The result is a pop-up function a And the content
First, the b property caller calls the current b function a (which refers to a, the parent of the current b function b), so the result is function a(){b(); };
If you know caller and callee, can you combine the two into one
function b(){
alert(b.caller);
};
You can see from this code that the b function calls the b function name, which is inconvenient when the function name changes, so we need to replace the b inside
Before we know what method to use to point to the current object, let's modify 1:
(function a(){
b();
})();
function b(){
alert(arguments.callee.caller);
};
As you can see from the code, we replaced the b function with arguments.callee, so we solved the problem of 1...
That's all for this article, I hope you enjoy it.