Home > Web Front-end > JS Tutorial > body text

A new understanding of this pointer in JavaScript

怪我咯
Release: 2017-07-04 15:11:16
Original
1049 people have browsed it

This article mainly introduces the new understanding and sharing of this pointer in JavaScript. This article explains the method calling mode, function calling mode, constructor calling mode, and Apply calling mode. To understand the this pointer in , friends who need it can refer to

. The understanding of this has always been that it can be used and can be used, but it has not delved into its essence. This time, I gained a deep understanding through "JavaScript The Good Parts". (All debugging can be seen in the console, browser F12 key)

Let’s take a look at this together.

When we declare a function, in addition to the parameters (formal parameters) when it is defined, each function will also have two additional parameters, one is this and the other is arguments (actual parameters). arguments are the parameters actually received by the function, which are an array-like array. I will only give a brief introduction to arguments, focusing on the this pointer.

In Object-oriented programming, this is very important, and its value depends on the calling mode. In JavaScript, there are a total of 4 calling modes: method calling mode, function calling mode, constructor calling mode, and apply calling mode.

Method calling mode

When a function is used as a property of an object, we usually call the function a method of the object. When this method is called, this will point to the object to which the method belongs.

The code is as follows:

<script type="text/javascript">
    var people = {
        name : "Yika",
        sayName : function(){
            console.log(this.name);   //"Yika"
                        //this已经绑定在了people对象上了
        }
    }
    people.sayName();
</script>
Copy after login

As shown in the chestnut, this points to the sayName object. This method of obtaining the context of the object through this is a public method. (publice method)

Function calling mode

When a function is called and is not a method on an object, it is called as a function.

When called in this mode, this will point to the window object, even if this function may be called in an external function, let's look at an example.

The code is as follows:

<script type="text/javascript">
    var name = "window-Yika";
    var people = {
        name : "people-Yika",
        student : function(){
            console.log(this);   //这里的this绑定的是对象people
            function sayName(){
                var name = "sayName-Yika";
                console.log(this.name); //window-Yika
          //即使sayName函数本身和它所在的people对象都有name值,但是this是指向window的
            };
            sayName();
        }
    }
    people.student();
</script>
Copy after login

Looking at it this way, you probably know how to solve the "design error" of JavaScript.

Yes, just cache this in the student function, which is line 6. Then transfer this to the sayName function through a variable and you can solve it!

The code is as follows:

var people = {
        name : "people-Yika",
        student : function(){
            var self = this; //将this缓存起来
            function sayName(){
                var name = "sayName-Yika";
                console.log(self.name);  //"people-Yika",此时的self指向的是people对象
            };
            sayName();
        }
    }
Copy after login

Constructor calling mode

When JavaScript talks about constructors, there will be something in mind: "Function names are capitalized ! Use newoperator when calling! "The function name is capitalized for easy understanding, in order to standardize the naming of constructors. But have you ever delved into why you need to use new? If you call a function with new in front of it, the function background will create a new object pointing to the prototype of the function, and this will also be bound to the new object. JavaScript is a language based on prototype inheritance. Students who are not very clear about the prototype can check the information by themselves. I will focus on this.

Let’s first take a look at what a constructor generally looks like.

The code is as follows:

<script type="text/javascript">
    function People(name){
        this.name = name;    //这里的this,用new调用后便指向了新对象Yika    
     this.sayName = function(){
          console.log(this.name);  //输出
      }
    }
  var Yika = new People("Yika");  
   Yika.sayName();  //输出“Yika" ,因为Yika是通过new调用得来的,this都绑定在了Yika对象上。
</script>
Copy after login

At first glance, it seems not easy to understand. Why did this in the function just point to the window? Now there is no need to cache it. What about pointing to the People function?

It doesn't matter. Didn't I just say that when the function is called through new, it will do "bad things" behind the scenes? Let's take a look at what it has done.

The code is as follows:

<script type="text/javascript">
    function People(name){
        var that = {};   //坏事一:自己生成一个对象
        that.name = name;
        that.sayName = function(){
            console.log(that.name);
        };
        return that;    //坏事二,自己会改变return的行为,return刚生成的对象
    }
    var Yika = People("Yika"); //这里可以省略new,模仿调用new操作符
    Yika.sayName(); //和刚才一样输出"Yika"
</script>
Copy after login

If you look at it this way, you will understand clearly. new will not only generate an object, but also automatically return the object, so it is natural this points to this new object.

Be sure to use new to call the constructor, otherwise there will be no warning if something goes wrong. All capital letters are still very necessary.

Apply calling mode

The apply method allows us to construct an array of parameters to pass to the calling function, and also allows us to change the this value.

function.apply(this bound value, arguments parameter array)

There are too many things that can be said about apply. I will only give you a few examples to help you understand:

The code is as follows:

<script type="text/javascript">
    function People(name){
        this.name = name;
        this.sayName = function(){
            console.log(this.name);   //sayName这个方法是属于People构造函数的
        }
    }
    function Student(name){
        People.apply(this, arguments);//借用构造函数的集成方式,就是在Student构造函数里,通过apply调用People构造函数,并改变People的this值
                                      //这样每次创建Student实例时,都会调用People构造函数
    }
    var student = new Student("Yika");
    student.sayName(); //输出“Yika”
</script>
Copy after login

We can easily modify the this binding object of the function through apply. The method call, which is similar to apply, also has the same effect. Interested students can search and learn by themselves. .

Okay, we have finally finished talking about the four calling modes for changing this. The method calling mode and the constructor calling mode will be used more and are more important. As for the function calling mode, we need to learn it. Avoid the pitfalls.

If there are any errors, please report them in time and I will correct them as soon as possible to prevent misleading others. Thank you!

The above is the detailed content of A new understanding of this pointer in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!