Call and apply

Source: Internet
Author: User

This article according to some of the big guys in the reply finishing, if there is deeper insight, welcome to join the discussion ~ ~

In JS oop, this is often defined as:

function= {    ' fish ',    function() {        Console.log (  the. food);    }        } var New  //I Love fish

Call and apply are used to dynamically change this, and when an object does not have a method, but other methods are available, you can use call or apply to manipulate the other object's methods:

function= {    ' fish ',    function() {        Console.log (  the. food);    }        } var New  //I love fishvar whitedog = {food: ' bone '//I Love Bone

The difference between calls and apply is that call needs to pass parameters in order, and apply is to pass the parameters in the array.

Therefore, the number of parameters of a function in JS is not fixed, you can use apply, the parameter push into the array to pass, you can also use the arguments object to traverse to get all parameters, when the parameters are clearly known, the number can be used when the call.

As an example:

The DOM node selected through document.getElementsByTagName is an array-like object, but it cannot be applied using push, pop, etc. under the array, we can:

var domnodes = Array.prototype.slice.call (document.getElementsByTagName (' * '));

This way the domnodes can use all the methods under the array.

Call and apply

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.