Use of JavaScript apply, call, and bind methods __java

Source: Internet
Author: User

First, these three methods are the scopes that extend the function by changing the point of the This object of the function. Each function contains three methods that are not inherited. They are used in the same ways to invoke a function in a specific scope. The first argument is the object to point to. Can be passed parameters, the way to pass the parameter is different. Apply, call return function run result, bind generates a function to pass the parameter: apply (obj, [parameter 1, Parameter 2, ...]), call (obj, parameter 1, parameter 2, ...), bind at the generated function execution place to pass the parameter.

> name = ' li Ming ' '
li Ming '
> Age = ' > Let
people = {name: ' Little Red ', age:17}
undefined
> Func tion SayHello () {
... console.log ("hello!" + this.name);
... }
Undefined
> SayHello ()
hello! liming
undefined
> sayhello.apply (People)//This points to the People object
hello!        //Direct return to run results
undefined
> Sayhello.call (People);//This points to people object
hello! Little Red        //Direct return to run results
undefined
> Sayhello.bind (SayHello)  //Return a new function
[Function:bound SayHello]
> Sayhello.bind (People) ()  //Can be used in (parameters) to
hello! small red
undefined
> Newsayhello = Sayhello.bind (People)
[function:bound SayHello]
> Newsayhello ()
hello! Xiao Hong

Later found a section of Function.prototype.apply.call (FN, obj, args) code, what ghost ...

After reading the This object that knows to bind a function, you can write this: fn.apply (obj, args), but if the function customizes the Apply method, the This object to bind a function can only be written as Function.prototype.apply.call (FN, obj, args). Simplified method Use (ES6): reflect.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.