The usage and difference between apply and call in JS

Source: Internet
Author: User

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

// 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 var function () {  Console.log (this = =window);} Test.apply (null); // truetest.call (undefined); // true

Usage

1.methods of "hijacking" others (personal feelings are also inherited )

// The logname method in Foo will be referenced by bar, this points to bar var foo = {  name:"mingming",  logName:function() {    Console.log (  this. name);}  } var bar={  name:"Xiaowang"};foo.logname.call (bar); // Xiaowang

2. Implementing Inheritance

function Animal (name) {     this. Name = name;        This function () {       Console.log (this. Name);     }   }     function Cat (name) {    Animal.call (this, name);  }     var New Cat ("Black cat");    // Black Cat

The usage and difference between apply and call in JS

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.