JS in this, apply, call, bind (classic interview questions)

 

1, What is this

In JavaScript, this can be a global object, the current object or any object, it all depends on function is called, the object of this binding function that is performed by context (context).

To help understand, let's look at a piece of code together:

Copy the code
// invoked as an object method 
var Test = { 
    A:. 5, 
    B:. 6, 
    SUM: function () { 
        return this.a + this.b; // = Test where the this 
    } 
} 
Alert (test.sum ()) ; // 11
Copy the code

As the object calls this easy to understand, this is equivalent to the sum of the test object is the caller of Appeal, and if called as a function this =?

Copy the code
// call as a function of 
A =. 4; 
B =. 3; 
function SUM () { 
    return this.a + this.b; // = window where the this 
} 
Alert (SUM ()); //. 7
Copy the code

At this function sum is a global function as a window object, so the caller sum for the window, that is, this = window.

Copy the code
Test = {var 
    A:. 5, 
    B:. 6, 
    SUM: function (A, B) { 
        function getA (A) { 
            this.a = A; // adds a window in the global variable A 
            return this.a; / / = window where the this 
        } 
        function getB (b) { 
            this.b = b; // b adds a global variable in the window 
            return this.b; // = window where the this 
        } 
        return getA (a) + getB (B); 
    } 
} 
Alert (test.sum (4,3-)); //. 7 
Alert (A); //. 4      
Alert (B); //. 3
Copy the code

 In this case, we want getA () and the value returned getB () is test.a and test.b, but this time the closure function (i.e., function in the function) and getB getA this does not point in the test example, how to do it? We might as well try the following method:

Copy the code
Test = {var 
    A:. 5, 
    B:. 6, 
    SUM: function () { 
        var = Self the this; // this = test examples herein 
        function getA () { 
            return self.a; 
        } 
        function getB () { 
            return Self .B; 
        } 
        return getA () + getB (); 
    } 
} 
Alert (test.sum ()); 
Alert (A); // given here: A IS Not defined 
Alert (B); // given here: a is not defined
Copy the code

In sum function test object with a local variable to save the current self this pointer, so that the closure function and getB getA test will be able to obtain the property instance by self variable.

This seems able to solve the problem of closure function in this, but, if the call is not a test sum function instance of it, this time var self = this can also play a role, access to an instance of test do?

 2, the context (this) when using call, apply and changing the function execution bind

Use call, apply and bind context functions can be changed, then we look at the specific differences between these reporters it.

call method:

Syntax: call ([thisObj [, arg1 [, arg2 [, [, .argN]]]]])

It is defined: a call to an object method, replace the current object to another object.

Description: call method can be used in place of another object calls a method. The method may call a function of the object context specified by the new object from the initial thisObj context change.

     If no thisObj parameters, then the Global object is used as thisObj.

apply method:

语法:apply([thisObj[,argArray]])

Definition: Application of a method of an object, replacing the current object with another object.

Note: If argArray not a valid arguments object array or not, it will cause a TypeError.

        If no parameter argArray any thisObj, then the object is used as Global thisObj, and are not pass any parameters.

bind method:

Syntax: bind (thisArg [, arg1 [, arg2 [, ...]]])

Definition: The function of receiving a plurality of parameters into accepts a single parameter.

Description: length function bind () method returns (shape parameter amount) of equal-size parameter by subtracting the amount of the original function of the amount of actual parameters (all parameters after the first argument) into bind () method, since the transmission in the argument will bind to the binding parameter of the original function.

Oh mother, we talked about things so much theory, I fainted, or look at an actual example:

Copy the code
Test = {var 
    A:. 5, 
    B:. 6, 
    SUM: function (A, B) { 
        var = Self the this; 
        function getA () { 
            return self.a; 
        } 
        function getB () { 
            return self.b,; 
        } 
        Alert ( A); 
        Alert (B); 
        return getA () + getB (); 
    } 
} 
var {obj = A: 2, B:}. 3; 
Alert (test.sum.call (obj, 4,5)); // when calling self = this = obj, alert sequence 4,5,5 
Alert (test.sum.apply (obj, [6, 7 are])); // call when the self = this = obj, alert sequence 6,7,5  
var sum = test.sum.bind (obj, 8 ); // here to return only a function of a parameter sum (b)
alert (sum (9)); // call when the self = this = obj, alert sequence 8,9,5
Copy the code

From the above example we can clearly see the difference between the call, apply and bind. Call and apply which are similar, but different mass participation situation (apply the second argument is an array or arguments), they are direct direct execution function;

And bind another function test.sum simplify global function sum (b), sum (b) only need to pass a parameter.

3, to solve this annoying in js

call, apply and bind can be applied to inheritance, where not too much to say, online there are many such examples, reference: http://blog.csdn.net/wyyfwm/article/details/46349071

And this time I want to talk about something troublesome about this I encountered.

Copy the code
<button id="btn">烦人的this</button>
<script>
    var test = {
        isSum: true,
        sum: function (event, a, b) {
            if (this.isSum) {   // this = button,这个时候不会执行alert(a+b)
                alert(a + b);
            }
        }
    }
    var button = document.getElementById("btn");
    button.addEventListener("click", test.sum, false);
</script>
Copy the code

Here we can find the problem, and when the ID button is clicked btn will trigger test.sum function, but this time this = button, and the parameters a, b how to pass it?

Here it is possible to use the bind function, the function will test.sum simplified as another new function, passing the parameters a and b, we look at the following code:

Copy the code
<button id="btn">this</button>
<script>
    var test = {
        isSum: true,
        sum: function (a, b,event) {
            if (this.isSum) {  // 此处this=test,this.isSum = true
                alert(a + b);  // 9
            }
        }
    }
    var button = document.getElementById("btn");
    button.addEventListener("click", test.sum.bind(test,4,5), false);  // 此处test.sum.bind(test,4,5)返回一个新的函数function(event),
</script>
Copy the code

From the above we can see the code test.sum.bind (test, 4,5) function returns a new function (event), test, 4,5 test.sum are bound to the context, the parameters a, parameter b in.
When the ID of the button is clicked btn test.sum function triggers, this time to change the function of this = test, a = 4, b = 5.

This can solve this problem and parameter passing when the event is bound, including the now popular js framework of binding events, such as jQuery, signals.min.js and so on.

Guess you like

Origin www.cnblogs.com/web-chuanfa/p/11294765.html