Application of Bind,call,apply method in JS

Source: Internet
Author: User

Recently with the JS class to write things, found an extremely painful thing, that is encapsulated in the class method of the this pointer will often change the point, lost context, resulting in a program error or crash.

Like what:

function Obj () {
This.type = "obj";
}
Obj.prototype = {
Show:function () {
Ettimeout (function () {
Console.log (This.type);
},300)
}

var obj = new obj ();
Obj.show (); undefined

Fortunately, the great JS has a number of ways to solve this problem. We can directly save a pointer to the context such as var self = this; Then use the cached self pointer, but JS contains Bind,apply,call and other useful methods to specify the context.

Syntax: Fn.bind (obj,arguments)

Fn.apply (obj,arguments)

Fn.call (obj,arguments)

Difference:

1.bind returns a method, while the remaining two calls the function directly;

2. The first parameter is the same, the context object is specified, the second parameter is an array, and the call corresponds to the shape

Reference: http://www.css119.com/archives/1376

Application of Bind,call,apply method in JS

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.