


Javascript technical difficulties: the connection between apply, call and this_javascript skills
1.apply definition
apply: Call the function, replace the this value of the function with the specified object, and replace the parameters of the function with the specified array.
Syntax: apply([thisObj[,argArray]])
thisObj
Optional. The object to use as this object.
argArray
Optional. A set of arguments to be passed to the function.
2.call definition
call: Call a method of an object and replace the current object with another object.
Syntax: call([thisObj[, arg1[, arg2[, [, argN]]]]])
thisObj
Optional. The object to be used as the current object.
arg1, arg2, , argN
Optional. The parameter list that will be passed to the method.
3. The difference between the two
The second parameter of call can be of any type, while the second parameter of apply must be an array or arguments.
The definitions are also different.
4. Example analysis
(1)Official example:
function callMe(arg1, arg2){ var s = ""; s += "this value: " + this; s += "<br />"; for (i in callMe.arguments) { s += "arguments: " + callMe.arguments[i]; s += "<br />"; } return s; } document.write("Original function: <br/>"); document.write(callMe(1, 2)); document.write("<br/>"); document.write("Function called with apply: <br/>"); document.write(callMe.apply(3, [ 4, 5 ])); document.write(callMe.call(3, 4, 5 )); // Output: // Original function: // this value: [object Window] // arguments: 1 // arguments: 2 // Function called with apply: // this value: 3 // arguments: 4 // arguments: 5
The first one uses apply: Definition: Call a function and replace the this value of the function with the specified object. Call the function callMe, and use the specified object 3 to replace this in the callMe function. At this time, this here is changed from the previous [object Window] becomes 3. The first one uses call: Definition: Call a method of an object and replace the current object with another object. Call the method of the object callMe and replace the object in callMe with another object 3. From the analysis of these results, it can be seen that both of them use the object in the specified object or the specified value to change this in the object. It can also be said that the object (this) in a function "hijacks" the object (this) in another function to be executed. In fact, this raises a question: What exactly is this? Why is it so important to go through so much trouble to change its direction again and again? Portal: Technical Difficulties of JavaScript (Part 3) - Detailed explanation of this, new, apply and call (the content here is great, definitely enough for you to drink a pot) (2) Example:
function zqz(a,b){ return alert(a+b); } function zqz_1(a,b){ zqz.apply(zqz_1,[a,b]) } zqz_1(1,2) //->3
Analysis: According to the definition: call a function and replace the this value of the function with the specified object,
Here the function zqz is called and the this value of the zqz function is replaced with the specified object zqz_1.
Please note that the function name in js is actually an object, because the function name is a reference to the Function object!
function add(a, b) { alert(a + b); } function sub(a, b) { alert(a - b); } add.call(sub, 3, 1); // 4
Analysis: According to the definition: Call a method of an object and replace the current object with another object.
Here is the method of calling the object add and replacing the current object sub with the add object;
Another example:
function zqz(a,b){ this.name=a; this.age=b; alert(this.name+" "+this.age); } function zqz_1(a,b){ zqz.apply(this,[a,b]) //我们亦可以这么写 zqz.apply(this,arguments) } zqz_1("Nic",12) //Nic 12
Analysis: According to the definition: call a function and replace the this value of the function with the specified object,
The function zqz is called here, and the this of the function zqz is replaced with the specified object this.
Another example:
<input type="text" id="myText" value="input text"> function Obj(){ this.value="对象!"; } var value="global 变量"; function Fun1(){ alert(this.value); } Fun1(); //global 变量 Fun1.call(window); //global 变量 Fun1.call(document.getElementById('myText')); //input text Fun1.call(new Obj()); //对象! Fun1(); //global 变量
分析:定义:调用一个对象的方法,用另一个对象替换当前对象。
调用Fun1对象的方法,用window对象替换当前Fun1中的对象。
调用Fun1对象的方法,用input中对象替换当前Fun1中的对象。
调用Fun1对象的方法,用新new出来的obj中的对象替换当前Fun1中的对象。
最后再总结一下:
如果在javascript语言里没有通过new(包括对象字面量定义)、call和apply改变函数的this指针,函数的this指针都是指向window的。
ps:apply的其他巧妙用法:
大家会不会觉得既然apply和call的用法差不多,那么为什么还同时存在这两种方法呢?完全可以丢掉一个呀。后来才发现一篇文章中讲到apply因为它所传参数为数组这一特点还有许多其他的妙用。
a) Math.max 可以实现得到数组中最大的一项:
因为Math.max 参数里面不支持Math.max([param1,param2]) 也就是数组,但是它支持Math.max(param1,param2,param3…),所以可以根据apply的特点来解决 var max=Math.max.apply(null,array),这样轻易的可以得到一个数组中最大的一项。(apply会将一个数组转换为一个参数接一个参数的传递给方法)
这块在调用的时候第一个参数给了一个null,这个是因为没有对象去调用这个方法,只需要用这个方法帮助运算,得到返回的结果就行,所以直接传递了一个null过去。
b) Math.min 可以实现得到数组中最小的一项:
同样和 max是一个思想 var min=Math.min.apply(null,array)。
c) Array.prototype.push 可以实现两个数组合并:
同样push方法没有提供push一个数组,但是它提供了push(param1,param,…paramN) 所以同样也可以通过apply来转换一下这个数组,即:
var arr1=new Array("1","2","3"); var arr2=new Array("4","5","6"); Array.prototype.push.apply(arr1,arr2);
也可以这样理解,arr1调用了push方法,参数是通过apply将数组装换为参数列表的集合。
d) 小结:通常在什么情况下,可以使用apply类似Math.min等之类的特殊用法:
一般在目标函数只需要n个参数列表,而不接收一个数组的形式([param1[,param2[,…[,paramN]]]]),可以通过apply的方式巧妙地解决这个问题。

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

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.
