JavaScript中的this/call/apply/bind

A, this

1. What is this

Is an important presence in most languages ​​this keyword, JS naturally no exception, meaning the expression of diverse and even some complex, profound understanding this is to learn JS, object-oriented programming is very important part.

What 2.this representatives

This context represents the function (method) performed (context, similar to the article you want to know, to understand the context of the article you can clearly understand the relationships).

But in JavaScript this is not fixed, it will change with the execution environment is changed.

1. In the method, this method indicates that the object belongs.

2. If used alone, this represents a global object.

3. In the function, this represents a global object.

4. In the function, in the strict mode, the this is undefined (undefined).

5. In the event, this event represents the element receiving.

6. Similar call () and apply () refer to this method may be any object.

3. Binding of this

Dynamic switching this, of course, created a tremendous amount of flexibility is JavaScript, but also makes the program more difficult and ambiguous. Sometimes, this needs to be fixed, to avoid unexpected situation. JavaScript provides call, apply, bind these three methods, is switched to / fixed to this.

4.this point

1. In this refers to the general global object function approach

function test(){
    this.x = 1;  //这里this就是window
    console.log(this.x);
  }
  test(); // 1

JS provides that the function of this, when the function is called to determine, it refers to the function of the current operating environment.

2. As an object method call, this refers to the superior object

var x =3;
function test(){
  alert(this.x);
}
var o = {
  x:1,
  m:test 
};
o.m(); // 1

If the method of the object as a function, this refers to the method object.

3. As a constructor call, this refers to a new object

function test(){
    console.log(this);
  }
  var o = new test();
       test();
//可以看出o代表的不是全局对象

Keywords new role is to call a function and get the return value of them, just call the process a little special. In the code example above. When the function is called test new keywords, internal order performed the following steps:

(1) Create an empty object.

(2) the empty object prototype, this prototype point constructor.

(3) the value of the empty object assigned to this internal function (this is the object of the empty).

(4) perform the function body of code, to bind this key-value pair of the object.

(5) return this, it calls the new keyword oop as a function of the return value.

Therefore the constructor of this, is still to determine its point, the point is that the current instantiated object when the constructor is called new keywords.

4. The function of this arrow
arrow ES6 function is a new feature, the most important feature is that it captures it in the context of this as their own this, or that arrow function itself is not this, it will follow this external environment . That is, the function and its internal arrow is outside of this consistent.

this.a=20
var test={
    a:40,
    init:()=>{
        console.log(this.a)
        function go(){
            this.a=60
            console.log(this.a)
        }
        go.prototype.a=50
        return go
    }   
}

var p=test.init()
p()
new (test.init())()
//输出 20 60 60 60

The change point

Dynamic switching this, of course, created a tremendous amount of flexibility is JavaScript, but also makes the program more difficult and ambiguous. Sometimes, this needs to be fixed, to avoid unexpected situation. JavaScript provides call, apply, bind these three methods, is switched to / fixed to this.

bind methods and apply, call slightly different, bind method returns a new function that will be called after the execution, but apply, call will be executed immediately.

二、Function.prototype.bind()

bind () method main function is to bind to a target, bind () will create a function, the value of this object's function in the body is bound to the value of the first parameter passed bind (), for example : f.bind (obj), in fact, can be understood as obj.f (), the function f at this time point the body of this nature is obj;

Example:

function f(y, z){
    return this.x + y + z;
}
var m = f.bind({x : 1}, 2);
console.log(m(3));
//6

The method herein will bind its binding to the first argument to the function F this body, so this point, i.e., where {x: 1} objects from the second parameter, in turn passed to the original function, where the second parameter 2, i.e., the parameter y is a function f, when m (3) of the last call, where z 3 is the last parameter, the execution result is 1 + 2 + 3 = 6 step process parameter in fact, the process is a typical function currying process (Curry).

Three, call / apply

1. Definitions

Each function contains two methods of non-inherited: call () method and apply () method.

call and apply can be used to redefine the function of the execution environment, this is directed; all call and apply a function to change the running context, i.e. context exists, in other words, is to change the functions that this point.

2. Grammar

call()

Call an object's method, replacing the current object with another object, another object can inherit property, its syntax is:

Function.call(obj[, param1[, param2[, [,...paramN]]]]);

obj: The object will replace the Function class in this subject
params: string parameter list

Description: call method can be used instead of a call to another object method, an object method call may be a function of the context for the specified obj new context change from the initial object obj parameter if no, then the object is used to Global obj.

apply()

And call () method of the same, but different parameter list, the syntax:

Function.apply(obj[, argArray]);

obj: Function This object will replace this object class
argArray: This is an array, it will be passed as a parameter Function

Note: If not a valid array argArray arguments object or not, this would result in a TypeError, and if no argArray any parameter obj, then the object is used as Global obj.

3. similarities and differences

Same point

The same point call () and apply () method is the role of these two methods is the same. Are called in a scope function, the function value set in the body of this object, functions to expand the scope on which to run.

In general, this always points to the object call a method, but when using the call () and apply () method will change the point of this, look at an example:

function add(a, b) {
    return a + b;
}

function sub(a, b) {
    return a - b;
}

console.log(add.call(sub, 2, 1));//3

Why add.call (sub, 2, 1) the execution result is 3, because the call () method changes the point of this, so that sub can call the add method, which is used to carry out sub contents add in, and then look one example:

function People(name, age) {
    this.name = name;
    this.age = age;
}

function Student(name, age, grade) {
    People.call(this, name, age);
    this.grade = grade;
}

var student = new Student('小明', 21, '大三');
console.log(student.name + student.age + student.grade);//小明21大三

In this case, we did not give the name and age of the Student assignment, but the presence of these two values property, this is thanks to the call () method, it can change the point of this.
In this example, People.call (this, name, age ); this represents the Student, which is said before, making the Student method People can call, because the People have this.name = name; and other statements, which will create the attribute name and age of the Student.

To sum it up is to call () brackets allow objects to inherit property parentheses around the function.

As apply () method and also the role of call () method like, you can write:

People.apply(this, [name, age]);

Or write:

People.apply(this, arguments);

Here arguments and [name, age] are equivalent.

difference

From the definition may be seen, call () and apply () is different from the reception parameters in different ways.

1.apply () method takes two parameters, a scope is (this) function to run, the other array of parameters.
2.call () method does not necessarily accepts two parameters, scopes (this) is the first parameter function operation, but must be passed to the function enumerated.

In the case of a target parameter, if the formal parameter is the time of the array, such as before the apply () method example which passed parameter arguments, this parameter is an array type, and when calling Person list parameter corresponding identical ( Person and Student is a list of the first two parameters are the same) can adopt apply () method.

However, if the argument list Person is such that (age, name), and the parameter list Student is (name, age, grade), we can use call () method to achieve, i.e. which directly specifies the parameter list corresponding values position Person.call (this, age, name).

发布了45 篇原创文章 · 获赞 157 · 访问量 15万+

Guess you like

Origin blog.csdn.net/liuyifeng0000/article/details/104563241