


In-depth understanding of the difference between apply() and call() methods in javascript_javascript skills
If you have never been exposed to dynamic languages, it will be a magical and weird feeling to understand JavaScript with the way of thinking of compiled languages, because things that are consciously impossible often happen, and even feel unreasonable. If you are learning When you encounter this feeling in the process of JavaScript, a free and ever-changing language, then from now on, please put down your "prejudice", because this is definitely a new continent for you, and let JavaScript slowly melt away from the past. Set a solidified programming consciousness and inject new vitality!
Okay, let’s get down to business. First, understand the dynamically changing runtime context characteristics of JavaScrtipt. This feature is mainly reflected in the use of the apply and call methods.
The difference between apply and call is just one sentence,
foo.call(this, arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)
call and apply are both methods of Function.prototype, which are implemented internally by the JavaScript engine. Because they belong to Function.prototype, each Function object instance, that is, each method has call and apply attributes. Since they are attributes of the method , then their use is of course targeted at methods. These two methods are easy to confuse, because they have the same function, but they are used in different ways.
Same points: The two methods have exactly the same effect
Difference: The parameters passed by the method are different
Then what is the function of the method and what are the parameters passed by the method?
Let’s analyze the above foo.call(this, arg1, arg2, arg3).
foo is a method, this is the context-sensitive object when the method is executed, arg1, arg2, arg3 are the parameters passed to the foo method. The so-called context-sensitive objects when the method is executed here, if you have the basis of object-oriented programming, it is very It’s easy to understand, it’s this.
in the object after the class is instantiated.In JavaScript, code always has a context object, and the code processes this object. The context object is represented by the this variable, and this this variable always points to the object where the current code is located.
In order to better understand what this is, let’s give an example.
/创建一个A类 function A(){ //类实例化时将运行以下代码 //此时的执行上下文对象就是this,就是当前实例对象 this.message = “message of a”; this.getMessage = function(){ <SPAN style="WHITE-SPACE: pre"> </SPAN>return this.message; <SPAN style="WHITE-SPACE: pre"> </SPAN>} } //创建一个A类实例对象 var a = new A(); //调用类实例getMessage方法获得message值 alert(a.getMessage()); //创建一个B类 function B(){ this.message = ”message of b”; this.setMessage = function(msg){ <SPAN style="WHITE-SPACE: pre"> </SPAN>this.message = msg; <SPAN style="WHITE-SPACE: pre"> </SPAN>} } //创建一个B类实例对象 var a = new B();
It can be seen that classes A and B both have a message attribute (a member in object-oriented terms). A has a getMessage method to get the message, and B has a setMessage method to set the message. The power of call is shown below.
//给对象a动态指派b的setMessage方法,注意,a本身是没有这方法的! b.setMessage.call(a, “a的消息”); //下面将显示”a的消息” alert(a.getMessage()); //给对象b动态指派a的getMessage方法,注意,b本身也是没有这方法的!
This is the power of dynamic language JavaScript call!
It is simply "made out of nothing". The method of the object can be assigned arbitrarily, but the object itself has never had such a method. Note that it is assigned. In layman's terms, the method is lent to another object to complete the task. In principle The context object changes when the method is executed.
So b.setMessage.call(a, "a's message"); is equivalent to using a as the execution context object to call the setMessage method of the b object, and this process has nothing to do with b, and the effect is equivalent to a.setMessage(“a’s message”);
Because apply and call have the same effect, it can be said
The function of call and apply is to borrow other people’s methods to call, just like calling your own.
Okay, after understanding the similarities between call and apply--after their functions, let's take a look at their differences. After reading the above examples, I believe you probably know it.
From b.setMessage.call(a, "a's message") is equivalent to a.setMessage("a's message"), it can be seen that "a's message" is passed as a parameter in call,
So how does it express in apply? It’s not clear to explain directly. Apply needs to be combined with the application scenario to make it clear at a glance. Let’s design an application scenario:
function print(a, b, c, d){ alert(a + b + c + d); } function example(a, b , c , d){ //用call方式借用print,参数显式打散传递 print.call(this, a, b, c, d); //用apply方式借用print, 参数作为一个数组传递, //这里直接用JavaScript方法内本身有的arguments数组 print.apply(this, arguments); //或者封装成数组 print.apply(this, [a, b, c, d]); } //下面将显示”背光脚本” example(”背” , “光” , “脚”, “本”);
In this scenario, in the example method, a, b, c, d are used as parameters passed by the method. The methods use apply and call respectively to borrow the print method to call,
The last sentence is because the example method is called directly, so the context object this in this method is the window object.
So, except for the first parameter of the call and apply methods, which is the context object during execution, the other parameters of the call method will be passed to the borrowed method as parameters in turn, while apply has only two parameters, the second parameter Passed as an array. So it can be said as
The difference between the call and apply methods is that starting from the second parameter, the call method parameters will be passed to the borrowed method as parameters in turn, while apply directly puts these parameters into an array and then passes them, and finally the parameter list of the borrowed method It’s the same.
Application scenarios:
When the parameters are clear, you can use call. When the parameters are unclear, you can use apply to combine arguments
//例 print.call(window, “背” , “光” , “脚”, “本”); //foo参数可能为多个 function foo(){ <SPAN style="WHITE-SPACE: pre"> </SPAN>print.apply(window, arguments); }
The above article provides an in-depth understanding of the difference between the apply() and call() methods in JavaScript. This is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.