Use of call, apply, bind, slice in JavaScript

Source: Internet
Author: User

1. Reference http://www.cnblogs.com/coco1s/p/4833199.html2, due to the following
    • Apply, call, and bind are all pointers to the This object that is used to change the function;
    • Apply, call, bind the first parameter is the object that this is to point to, that is, the context you want to specify;
    • Apply, call, bind three can use the following parameters to pass the parameter;
    • Bind is the return function, which is convenient to call later; apply, call is called immediately
    • Slice is used to convert objects containing the length property (pseudo-array objects, such as arguments, Document.getelementbytagname results, {length:3}, and so on) into real array objects
3, examples such as the next call, apply, bind example:
varobj ={x:81,};varFoo ={getX:function() {        return  This. x;  }}console.log (Foo.getX.bind (obj) ()); //BayiConsole.log (Foo.getX.call (obj));//BayiConsole.log (foo.getX.apply (obj));//81
Use the bind () method when you want to change the context and not execute immediately, but rather when the callback executes. and Apply/call immediately executes the function
.
Bind Example:
var foo = {    1,    function() {        $ (' body '). On (' click ',  function(event) {            /**            /console.log (  this. bar);      // 1        }. Bind (this));}    }
Slice Example:
Array.prototype.slice.call ({length:3,0: "First", 1: "Second"})//["First", "second", undefined]

Use of call, apply, bind, slice in JavaScript

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.