this in Javascript points to

foreword

JavaScript's this always points to an object, and which object it points to is dynamically bound at runtime based on the execution environment of the function, not the environment when the function is declared.

this points to

Excluding the infrequently used with and eval, in practical applications, the direction of this can be roughly divided into the following four types.

❏ As a method call on an object.

❏ Called as an ordinary function.

❏ Constructor calls.

❏ Function.prototype.call or Function.prototype.apply call.

Let's introduce them separately.

1. as a method call on an object

When a function is called as a method of an object, this refers to that object:

        var obj = {
    
    
            a: 1,
            getA: function(){
    
    
              alert ( this === obj );    // 输出:true
              alert ( this.a );    // 输出: 1
            }
        };

        obj.getA();

2. as a normal function call

When the function is not called as a property of the object, which is what we often call the normal function method, this time always points to the global object. In browser JavaScript, this global object is the window object.

        window.name = 'globalName';

        var getName = function(){
    
    
            return this.name;
        };

        console.log( getName() );    // 输出:globalName

or:

        window.name = 'globalName';

        var myObject = {
    
    
            name: 'sven',
            getName: function(){
    
    
              return this.name;
            }
        };

        var getName = myObject.getName;
        console.log( getName() );    // globalName

Sometimes we encounter some troubles. For example, inside the event function of the div node, there is a local callback method. When the callback is called as a normal function, this inside the callback points to the window, but we often want it to point to the div node, see the following code:

        <html>
            <body>
              <div id="div1">我是一个div</div>
            </body>
            <script>

            window.id = 'window';

            document.getElementById( 'div1' ).onclick = function(){
    
    
              alert ( this.id );        // 输出:'div1'
              var callback = function(){
    
    
                  alert ( this.id );        // 输出:'window'
              }
              callback();
            };

            </script>
        </html>

At this point there is a simple solution, you can use a variable to hold the reference of the div node:

        function func(){
    
    
            "use strict"
            alert ( this );    // 输出:undefined
        }

        func();

In the strict mode of ECMAScript 5, this in this case has been stipulated that it will not point to the global object, but undefined:

        function func(){
    
    
            "use strict"
            alert ( this );    // 输出:undefined
        }

        func();

3. constructor call

There are no classes in JavaScript, but objects can be created from the constructor, and the new operator is also provided to make the constructor look more like a class.

Except for some built-in functions provided by the host, most JavaScript functions can be used as constructors. The appearance of the constructor is exactly the same as that of a normal function, the difference lies in the way they are called. When a function is called with the new operator, the function always returns an object. Usually, this in the constructor points to the returned object, as shown in the following code:

        var MyClass = function(){
    
    
            this.name = 'sven';
        };

        var obj = new MyClass();
        alert ( obj.name );     // 输出:sven

But when calling the constructor with new, there is another problem to be aware of. If the constructor explicitly returns an object of type object, then the result of this operation will eventually return this object, not the this we expected before:

        var MyClass = function(){
    
    
            this.name = 'sven';
            return {
    
        // 显式地返回一个对象
              name: 'anne'
            }
        };

        var obj = new MyClass();
        alert ( obj.name );     // 输出:anne

If the constructor does not return any data explicitly, or returns a non-object type of data, it will not cause the above problems:

        var MyClass = function(){
    
    
            this.name = 'sven'
            return 'anne';    // 返回string类型
        };

        var obj = new MyClass();
        alert ( obj.name );     // 输出:sven

4. Function.prototype.call or Function.prototype.apply call

Compared with ordinary function calls, Function.prototype.call or Function.prototype.apply can dynamically change the this of the incoming function:

        var obj1 = {
    
    
            name: 'sven',
            getName: function(){
    
    
              return this.name;
            }
        };

        var obj2 = {
    
    
            name: 'anne'
        };

        console.log( obj1.getName() );     // 输出: sven
        console.log( obj1.getName.call( obj2 ) );    // 输出:anne

The call and apply methods can well reflect the functional language features of JavaScript. In JavaScript, almost every code written in a functional language style is inseparable from call and apply. In the design patterns of many versions of JavaScript, call and apply are also used.

Guess you like

Origin blog.csdn.net/weixin_45172119/article/details/128728739