search
HomeWeb Front-endJS TutorialExamples and understanding of arguments, caller, callee, call, apply under javascript_javascript skills

Before mentioning the above concepts, I first want to talk about the implicit parameters of functions in JavaScript: arguments
Arguments
This object represents the parameters of the function being executed and the function that calls it.

[function.]arguments[n]
Arguments function: options. The name of the Function object currently executing. n: option. The 0-based index of the parameter value to be passed to the Function object.
Explanation

Arguments is a hidden object created in addition to the specified parameters when calling a function. Arguments is an object that is similar to an array but not an array. It is said to be similar to an array because it has the same access properties and methods as an array. The value of the corresponding single parameter can be accessed through arguments[n], and it has the array length attribute length. Also, the arguments object stores the parameters actually passed to the function, not limited to the parameter list defined by the function declaration, and the arguments object cannot be created explicitly. The arguments object is only available at the beginning of the function. The following example details these properties:

Copy code The code is as follows:

//arguments object usage.
function ArgTest(a, b){
var i, s = "The ArgTest function expected ";
var numargs = arguments.length; // Get the value of the passed parameter.
var expargs = ArgTest.length; // Get the value of the expected parameter.
if (expargs s = expargs " argument. ";
else
s = expargs " arguments. ";
if (numargs s = numargs " was passed.";
else
s = numargs " were passed.";
s = "nn"
for (i =0 ; i s = " Arg " i " = " arguments[i] "n";
}
return(s); // Return the argument list.
}

Added a code here to explain that arguments is not an array (Array class):

Copy code The code is as follows:

Array.prototype.selfvalue = 1;
alert(new Array().selfvalue);
function testAguments(){
alert(arguments.selfvalue);
}

Run the code and you will find that the first alert displays 1, which means that the array object has a selfvalue attribute with a value of 1, and when you call When calling the function testAguments, you will find that "undefined" is displayed, indicating that it is not a property of arguments, that is, arguments is not an array object.
Attached here is a simple method recommended by everyone:
Copy the code The code is as follows:

alert(arguments instanceof Array);
alert(arguments instanceof Object);


caller
Returns a reference to a function that The current function is called.
functionName.caller
functionName object is the name of the function being executed.
Explanation
For functions, the caller attribute is only defined when the function is executed. If the function is called from the top level, then caller contains null . If the caller attribute is used in a string context, the result is the same as functionName.toString, that is, the decompiled text of the function is displayed.
The following example illustrates the usage of the caller attribute:
Copy the code The code is as follows:

// caller demo {
function callerDemo() {
if (callerDemo.caller) {
var a= callerDemo.caller.toString();
alert(a);
} else {
alert("this is a top function");
}
}
function handleCaller() {
callerDemo();
}

callee

Returns the Function object being executed, which is the body of the specified Function object.

[function.]arguments.callee
The optional function parameter is the name of the Function object currently being executed.

Explanation

The initial value of the callee attribute is the Function object being executed. The

callee attribute is a member of the arguments object, which represents a reference to the function object itself, which is beneficial to the recursion of the anonymous
function or to ensure the encapsulation of the function, such as the recursive calculation of 1 to n in the example below The sum of natural numbers. And this attribute
is only available when the related function is executing. It should also be noted that callee has a length attribute, which is sometimes
used for verification. arguments.length is the actual parameter length, and arguments.callee.length is the
formal parameter length. From this, you can determine whether the formal parameter length is consistent with the actual parameter length when calling.

Example

Copy code The code is as follows:

// callee can print itself
function calleeDemo() {
alert(arguments.callee);
}
//For verifying parameters
function calleeLengthDemo(arg1, arg2) {
if (arguments.length==arguments.callee.length) {
window.alert("Verify that the formal and actual parameter lengths are correct!");
return;
} else {
alert( "Actual parameter length: " arguments.length);
alert("Formal parameter length: " arguments.callee.length);
}
}
//Recursive calculation
var sum = function(n){
if (n return 1;
else
return n +arguments.callee(n - 1)
}

Relatively general recursive function:
Copy code The code is as follows:

var sum = function (n){
if (1==n) return 1;
else return n sum (n-1);

When called: alert(sum(100));
The function contains a reference to sum itself. The function name is just a variable name. Calling sum inside the function is equivalent to calling
a global variable. It cannot well reflect that it is calling itself. At this time Using callee would be a better method.

apply and call

Both of them bind a function to another object to run. The only difference between the two is the way to define parameters:

apply(thisArg,argArray);

call(thisArg[,arg1,arg2...] ]);

That is, the this pointer inside all functions will be assigned thisArg, this It can realize the purpose of running a function as a method of another object

Instructions for apply

If argArray is not a valid array or is not an arguments object, it will result in a TypeError.
If neither argArray nor thisArg is provided, the Global object will be used as thisArg,
and no parameters can be passed.

Description of call

The call method changes the object context of a function from the initial context to the new object specified by thisArg.
If the thisArg parameter is not provided, the Global object is used as thisArg

Related tips:

There is another trick in applying call and apply, which is to use call and apply to apply another After a function (class), the current
function (class) has the methods or attributes of another function (class), which can also be called "inheritance". Look at the following example:
Copy code The code is as follows:

// Demonstration of inheritance
function base() {
this.member = " dnnsun_Member";
this.method = function() {
window.alert(this.member);
}
}
function extend() {
base.call(this);
window.alert(member);
window.alert(this.method);
}

As can be seen from the above example, extend can inherit the methods and properties of base after calling.

By the way, apply is used in the JavaScript framework prototype to create a pattern that defines a class.

The implementation code is as follows:
Copy code The code is as follows:

var Class = {
create: function() {
return function() {
this .initialize.apply(this, arguments);
}
}
}

Analysis: From the code point of view, this object only contains one method: Create, which returns a function, that is, a class. But this is also the
constructor of the class, which calls initialize, and this method is the initialization function defined when the class is created. In this way,
can implement the class creation mode in prototype

Example:
Copy code The code is as follows:

var vehicle=Class.create();
vehicle.prototype={
initialize:function(type){
this.type=type;
}
showSelf:function(){
alert("this vehicle is " this.type);
}
}

var moto=new vehicle("Moto") ;
moto.showSelf();


For more detailed information about the prototype, please visit its official website.

There are more exciting understandings of this in the comments, so I won’t add them here. You can take a look to deepen your understanding.
After reading the above code, that’s it. The following code is for those who want to see the effect immediately. Test more.
Copy code The code is as follows:

<script> <BR>/**//* <BR>* 인수 사용법, 실수 매개변수 및 형식 숫자를 얻는 방법 시연 <BR>*/ <BR>function argTest(a,b,c,d){ <BR>var numargs = 인수. length; // 전달된 매개변수의 값을 가져옵니다. <BR>var expargs = argTest.length; // 예상되는 매개변수의 값을 가져옵니다. <BR>alert("실제 매개변수 개수:" numargs) <BR>alert("자릿수 개수:" expargs) <br><br>alert(arguments[0]) <BR>alert(argTest [0] ) //undefine에는 이 사용법이 없습니다. <BR>} <BR>//argTest(1,2) <BR>//결과: 실제 매개변수 수는 2개입니다. ; 1; 정의되지 않음 <BR> //argTest(1,2,3,4,5) <BR>//결과: 실제 매개변수 수: 4;1; /*요약: js 매개변수 전달은 C#과 같은 문법 요구사항과 일치하지 않아야 하며, 응용 프로그램에 따라 매개변수를 추가하거나 축소할 수 있습니다. */ <BR>var test = function(){ <BR>var a = 0; <BR>var l = 0 <BR>while(l<arguments.length) <BR>{ <BR>a = 인수[l]; 🎜>l ; <BR>} <BR>alert(a) <BR>} <BR>test();//0 <BR>test(1,2);//3 <BR><BR>/ **//* <br>* 인수가 배열이 아닙니다(Array 클래스) <br>*/ <BR><BR>Array.prototype.selfvalue = 1; <br>//이것은 원본 사운드 객체 ​​렌더링에 대해 많은 비판을 받았습니다.<br>function testAguments(){ <BR>alert("arguments .selfvalue=" 인수.selfvalue); <BR>} <BR>/ /alert("Array.sefvalue=" new Array().selfvalue); <BR>/*위 호출은 모든 Array 객체의 자체 값을 나타냅니다. 1*/ <BR>//testAguments(); <BR>/* 정의되지 않은 결과는 인수가 배열 유형이 아님을 나타냅니다*/ <BR><BR>/**//* <br>* 함수의 호출자 속성을 보여줍니다. <br>* 설명: (현재 함수).caller: 현재 함수를 호출하는 함수에 대한 참조를 반환합니다. <BR>*/ <BR> <BR>function callerDemo() { <br>if (callerDemo.caller) { <br>var a= callerDemo.caller.arguments[0]; <BR>alert(a) <BR>} else { <BR> Alert("최고의 함수입니다."); <BR>} <BR>} <BR>function handlerCaller() { <BR>callerDemo() <BR>} <BR><BR>//callerDemo(); <br>//결과: 최상위 함수입니다. <br>//handleCaller("Parameter 1", "Parameter 2") <BR>//결과: 매개변수 1 <BR>/*요약: 호출자가 적용됩니다. <BR>*/ <BR><BR>/ **//* <br>* 함수의 호출 수신자 속성을 보여줍니다. <br>* 설명: 인수.callee: 초기 값은 익명 함수에 사용되는 실행되는 함수 개체입니다. <BR>*/ <BR>function calleeDemo() { <BR>alert(arguments.arguments. callee); <BR>} <BR>//calleeDemo(); <BR>//(function(arg0,arg1) {alert("도형의 개수:"args.callee.length)})(); <BR>/*요약: 다음과 같이 재귀를 구현하는 데 사용할 수 있습니다. */ <BR>var i = 0 <BR>var a = function(){ <BR>i = 인수[0]; if(i>100||i==0) <BR>alert(i); <BR>arguments.callee(i ) <BR>}; //결과는 128이며 실제로는 2의 7제곱입니다. <BR><BR><BR>/**//* <BR>* 적용 및 호출 함수의 사용법을 보여줍니다. <BR>* 참고: 이 함수는 실행할 다른 객체에 함수를 바인딩하는 것입니다. 두 함수는 매개 변수를 정의하는 방식만 다릅니다. <BR>* 적용 (thisArg,argArray); <br>* call(thisArg[,arg1,arg2...] ]) <br>* 즉, 모든 함수 내의 this 포인터에는 thisArg <BR> 값이 할당됩니다.*/ <BR> <BR>function ObjectA(){ <BR>alert(" ObjectA()") 실행; <BR>alert(arguments[0]); <BR>this.hit=function(msg){alert(msg)} <BR>this.info="저는 ObjectA 출신입니다" <br>} <br><BR>function ObjectB(){ <BR>alert("Execute ObjectB()"); <BR>//ObjectA() 메서드를 호출합니다. 동시에 ObjectA 생성자에서 이 모든 것은 ObjectB에서 this로 대체 <BR>ObjectA.apply(this,arguments);//ObjectA.call(this) <BR>alert(this.info) <br> } <br>//ObjectB('Parameter 0')/*요약: 일반적으로 피호출자와 함께 사용됩니다*/ <BR>var i = 0 <BR>function a(b) <BR>{ <BR> i <BR>if(i> 4) <BR>return i; <BR>else <BR>return 인수.callee.call(this,b) <BR>} <BR>alert(a(0)) <BR><BR>// 이 범위의 문제에 대해 알려주세요. <BR><BR>var value="global Variable"; <BR>function Obj(){ <BR>this.value="Object! "; <BR>} <br>function Fun1(){ <br>alert(this.value); <br>} <br>//Fun1(); <BR>//result: 전역 변수 <BR>/ /Fun1.apply(window); <BR>//결과: 전역 변수, 기본값 this=window <BR>//Fun1.apply(new Obj()) <BR>//결과: 객체, this=new Obj (); Obj의 this는 함수 객체 인스턴스 <BR></script>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools