Introduction to the Apply () method and call ()

Source: Internet
Author: User

We find that the real usefulness of apply () and call () is to extend the scope in which functions are run.

1. Each function contains two non-inherited methods: Apply () and call ().
2. They are used in the same way, and are called functions in a specific scope.
3, the receiving parameters are different, apply () receives two parameters, one is the function run scope (this), and the other is a parameter array. The first parameter of the call () method is the same as the Apply () method, but the arguments passed to the function must be enumerated.




Hello my Object glad to meet you!

Analysis: in Example 1, we found that the real use of apply () and call () is to be able to expand the scope of the function to run, if we want to implement the traditional method, see the following code:

See Accents's code, we find that to make the Helloname () function scoped on the object MyObject, we need to dynamically create the Helloname property of the MyObject, which points to the Helloname () function as a pointer, so that When we call Myobject.helloname (), the This variable inside the function points to MYOBJECCT, and you can call the internal other public properties of the object.
By analyzing example 2, we can see the real use of the call () and apply () functions, and in the actual project, it is necessary to deal with the actual flexibility!
A small problem: take a look at the case of the this variable when defining a function in a function

The execution results are the same as the following:

4. Bind () method
Browsers that support this approach are ie9+, firefox4+, safari5.1+, opera12+, and Chrome. It is a method that belongs to ECMAScript5. See examples directly:

Here, Saycolor () calls the Bind () method, passes in the O object, returns the Osaycolor () function, and in Osaycolor (), the value of this is an O object.

Introduction to the Apply () method and call ()

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.