The use of apply and call in the detailed JS

Source: Internet
Author: User

Objective

Both call and apply are intended to change the context in which a function is run, in other words, to change the direction of this within the function body .
Call and apply work exactly the same way, but accept parameters differently.

Method definition
Apply
Function.apply(obj,args)The method can receive two parameters:

obj: This object will replace the This object in the function class

args: This is an array or an array of classes, and the Apply method passes the elements in the collection as arguments to the called function.

Pager

The call method is the same as the first parameter of the apply method , except that the second argument is a list of arguments

In non-strict mode when our first argument is passed to null or undefined, this in the body of the function points to the default host object, which in the browser is the window

12345 vartest = function(){  console.log(this===window);}test.apply(null);//truetest.call(undefined);//true

Usage

The way to "hijack" someone else.

The logName method in foo will be referenced by bar, This points to bar

12345678910 var foo = {    name: "mingming"    logname: function () {      console.log ( this .name);    " } var bar={    name: "Xiaowang" foo.logname.call (bar); //xiaowang

Implementing inheritance

12345678910111213 function Animal(name){     this.name = name;     this.showName = function(){       console.log(this.name);     }   }   function Cat(name){    Animal.call(this, name);  }   var cat = new Cat("Black Cat");   cat.showName(); //Black Cat

In real-world development, you will often encounter this point to a scene that has been inadvertently changed.
There is a local fun method, when fun is called as a normal function , the inside of the fun points to the window, but we often want it to point to the # Test node, see the following code:

12345678 window.id="window";document.querySelector(‘#test‘).onclick = function(){  console.log(this.id);//test  var fun = function(){    console.log(this.id);  }  fun();//window}

With call,apply , we can easily solve this problem.

12345678 window.id="window";document.querySelector(‘#test‘).onclick = function(){  console.log(this.id);//test  var fun = function(){    console.log(this.id);  }  fun.call(this);//test}

Of course you can do the same, but in the strict mode of ECMAScript 5 , this case is defined as not pointing to the global object, but undefined:

123456789 window.id="window";document.querySelector(‘#test‘).onclick = function(){  var that = this;  console.log(this.id);//test  var fun = function(){    console.log(that.id);  }  fun();//test}
?
12345 functionfunc(){  "use strict"  alert ( this);  // 输出:undefined}func();

Other usage

Class Array

This is referred to as an array of classes for objects that meet the following conditions

1. With the Length property

2. Storing data by index

3. Methods such as Push,pop without arrays

Common class arrays have arguments,nodelist!

1234 (function(){  Array.prototype.push.call(arguments,4);  console.log(arguments);//[1, 2, 3, 4]})(1,2,3)

So I push a 4 in arguments .

Array.prototype.push Page can implement two array merges

The

Same push method does not provide an array of push, but it provides a push (Param1,param,... paramn)   So it is also possible to replace this array with apply, that is:

1234 var arr1= new array ( " 1 " " 2 " , "3" ); var arr2= new array ( "4" , Code class= "JS string" > "5" "6" ); array.prototype.push.apply (ARR1,ARR2); console.log (arr1); //["1", "2", "3", "4", "5", "6"]

It is also possible to understand thatarr1 invokes the push method, which is a set of parameters that can be assembled into a parameter list by using apply .

For example, I want to find the maximum value in the class array

1234 (function(){  varmaxNum = Math.max.apply(null,arguments);  console.log(maxNum);//56})(34,2,56);

Judging type

1234567 console.log(Object.prototype.toString.call(123)) //[object Number]console.log(Object.prototype.toString.call(‘123‘)) //[object String]console.log(Object.prototype.toString.call(undefined)) //[object Undefined]console.log(Object.prototype.toString.call(true)) //[object Boolean]console.log(Object.prototype.toString.call({})) //[object Object]console.log(Object.prototype.toString.call([])) //[object Array]console.log(Object.prototype.toString.call(function(){})) //[object Function]

The above is the use and call summary of all the content, welcome to actively comment on the discussion, but also hope that this article to learn JavaScript to help you.

The use of apply and call in the detailed JS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.