In depth understanding of the this keyword in Javascript

  • 2020-04-02 14:45:32
  • OfStack

Since the introduction of javascript, the understanding of this parameter has been ambiguous. Although there is a deep understanding, but also always feel that is the kind of floating on the surface, not fully clear.

However, there is a lot of misunderstanding about this parameter. So who is this parameter?

To understand this

This is a special object associated with the execution context. Therefore, it can be called a context object (that is, an object that indicates in which context the execution context is fired).

Any object can be used as the value of this in the context. Misunderstandings arise in some descriptions of the ECMAScript execution context and part of this. This is often incorrectly described as a property of a variable object. Again:

This is a property of the execution context, not a property of the variable object. This feature is important because, in contrast to variables,this never participates in the identifier resolution process. In other words, when this is accessed in the code, its value is retrieved directly from the execution context without any scope chain lookup. The value of this is determined only once in context.

Nonsense is not much, first look at a chestnut:

var test = function(){}; test.prototype = {
}; var myTest = new test();; console.log(myTest.hasOwnProperty("foo"));  //Output what & NBSP; & have spent & have spent < br / > console.log(myTest.hasOwnProperty("fun"));  //What is output

HasOwnProperty: is used to determine whether an object has a property or object with the name you gave it. It is important to note, however, that this method cannot check whether the property is in the prototype chain of the object, which must be a member of the object itself.

I don't know what the answer is in the viewer's mind, the correct answer is true,false.

console.log(myTest.hasOwnProperty("fun")); true

To understand why this is so, it is important to understand the role played by this above, the object to which it refers. In the book the essence of the javascript language, it is pointed out that there are four invocation modes in javascript:

1. Method invocation pattern
2. Function call mode
3. Constructor invocation mode
4. Apply invocation pattern

Among these modes, there are differences in how to initialize the key parameter this.

Method invocation pattern

When a function is saved as a property of an object, we call it a method. When a method is called, this is bound to the object. Notice that the bold sentence is the key:

//Create myObject. It has a value property and a increment method var myObject = {
    value: 0;
    increment: function(inc) {
        this.value += typeof inc ==='number'?inc:1; //Accept an optional parameter, if not a number, the default is the number 1
}; myObject.increment();
console.log(myObject.value);    // 1 myObject.increment(2);          //The incoming number 2
console.log(myObject.value);    // 3

Here, the method increment can use this to access the myObject object, so you can change the value of value. Furthermore, the binding of this to the object occurs when invoked.

Function call pattern

If a function is not a property of an object, it is called as a function, and this is bound to a global object, which the book says is a flaw in the design of the js language. If designed correctly, this should still bind to the this variable of the external function when the inner function is called. Regardless of whether the language design is correct or not, this variable is still bound to the object when the function is called in the pattern.

//Add a double method to myObject var myObject = {
    value: 0;
    increment: function(inc) {
        this.value += typeof inc ==='number'?inc:1; //Accept an optional parameter, if not a number, the default is the number 1
}; myObject.increment(2); myObject.double = function () {
    var that=this;  //Solution
    var helper= function () {
myObject.double();  //Call double
as a method console.log(myObject.getValue());   //6

That is to define a variable to the method and assign it to this, and then the inner function can access this through that variable, and by convention, that variable is called that.

Constructor invocation pattern

The constructor invocation pattern is what I mentioned in the example I gave at the beginning. If called with new in front of a function, a new object is created that connects to the function's prototype member, and this is bound to that new object. It sounds like a mouthful and hard to understand, so let's watch another demo:

//Construct a constructor function named Quo, an object with a status attribute var Quo = function(string){
    this.status =string;
}; Quo.prototype.get_status = function(){
    return this.status;
} var myQuo =new Quo("confuse");  //Construct a Quo instance console.log(myQuo.get_status());  //confuse

In short, when this under the Quo object is used to construct a new instance called new, this refers to the newly created myQuo object rather than to the Quo object itself.

In a word, the point is that this in a prototype is not the prototype object, but the calling object.

Going back to the first demo, it makes sense that when we execute (), this refers to the myTest object, so we generate a property foo with a value of "banana", so mytest.hasownproperty ("foo") returns true.

Apply invocation pattern

Because javascript is a functional object-oriented programming language, functions can have methods. The apply method lets us build an array of arguments and use it to call other functions. The apply method accepts two arguments, the first being the value of this to be bound and the second an array of arguments. Simply put, the apply method can hijack another object's methods and inherit another object's properties.

Knowledge is still shallow, if the article is not correct, please be sure to point out that it is too big to make people's children.

Related articles: