Home Web Front-end JS Tutorial Javascript technical difficulties: the connection between apply, call and this_javascript skills

Javascript technical difficulties: the connection between apply, call and this_javascript skills

May 16, 2016 pm 03:27 PM

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 
Copy after login

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 
Copy after login

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 
Copy after login

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 
Copy after login

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 变量 
Copy after login

分析:定义:调用一个对象的方法,用另一个对象替换当前对象。

调用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); 
Copy after login

也可以这样理解,arr1调用了push方法,参数是通过apply将数组装换为参数列表的集合。

d) 小结:通常在什么情况下,可以使用apply类似Math.min等之类的特殊用法:

一般在目标函数只需要n个参数列表,而不接收一个数组的形式([param1[,param2[,…[,paramN]]]]),可以通过apply的方式巧妙地解决这个问题。

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

jQuery Matrix Effects jQuery Matrix Effects Mar 10, 2025 am 12:52 AM

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of ​​the picture and uses jQuery to calculate the average color of each area. Then, use

How to Build a Simple jQuery Slider How to Build a Simple jQuery Slider Mar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Enhancing Structural Markup with JavaScript Enhancing Structural Markup with JavaScript Mar 10, 2025 am 12:18 AM

Key Points Enhanced structured tagging with JavaScript can significantly improve the accessibility and maintainability of web page content while reducing file size. JavaScript can be effectively used to dynamically add functionality to HTML elements, such as using the cite attribute to automatically insert reference links into block references. Integrating JavaScript with structured tags allows you to create dynamic user interfaces, such as tab panels that do not require page refresh. It is crucial to ensure that JavaScript enhancements do not hinder the basic functionality of web pages; even if JavaScript is disabled, the page should remain functional. Advanced JavaScript technology can be used (

How to Upload and Download CSV Files With Angular How to Upload and Download CSV Files With Angular Mar 10, 2025 am 01:01 AM

Data sets are extremely essential in building API models and various business processes. This is why importing and exporting CSV is an often-needed functionality.In this tutorial, you will learn how to download and import a CSV file within an Angular

See all articles