JS call apply bind simple understanding

Source: Internet
Author: User

The same point: JS in the call and apply method can change the context of a function execution, that is, you can change the function within the direction of this.
Difference: In the parameters of the call and apply methods, the first parameter is the specified context or the specified object, and the call () method passes in a variable, and the parameter passed in by the Apply () method is placed in the array to be passed in.

The bind () method is similar to the call () and the Apply () method, which can change the direction of this within the function.

The MDN explanation is that the bind () method creates a new function called a binding function that, when called, binds the binding function to the first parameter of the bind () method as it is created when it is passed into bind () The second and subsequent parameters of the method plus the binding function run when the parameters of the province are called as the parameters of the original function in order to invoke the original function.
If you just want to change the context and not execute the function, use the bind () method, and the call () or the Apply () method immediately executes the function.

Demo:

(function(){  varobj ={ID:1, Name:' Object ', Show:function() {Console.log (' Number:%d, Name: '%s ', This. ID, This. Name);    }  }; Obj.show ();//Number: 1, Name: Object    varLili ={ID:2, Name:' LiLi '  }; Obj.show.call (Lili);//Number: 2, Name: LiLiObj.show.apply (Lili);//Number: 2, Name: LiLiObj.show.bind (Lili) ();//Number: 2, Name: LiLi})();

Application:

(function(){  varARR1 = [1, 3, 5, 7, 9]; //Maximum value:Console.log (Math.max.apply (NULL, arr1));//9  //Minimum Value:Console.log (Math.min.apply (NULL, arr1));//1  varARR2 = [' A ', ' B ', ' C ', ' d ']; //Array AppendArray.prototype.push.apply (arr1, ARR2); Console.log (arr1);//[1, 3, 5, 7, 9, "a", "B", "C", "D"]})();

JS call apply bind simple understanding

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.