Comparison of the use of this keyword in javascript

Source: Internet
Author: User

Comparison of the use of this keyword in javascript

The This keyword is used in JavaScript, but it is much more than that. It is critical to be familiar with the various uses of this keyword.

This is sometimes the context that we often say, the object of this thing. It's flexible, and sometimes you see it as an object, sometimes a window host object.

1.this pointing to the host object
function myWindow() {    this.id = 1; // 等价于window.id = 1    console.log(this); // 这里的this就是window了    console.log(this.id); // 1}myWindow();

This situation is more common, that is, the case of the host object, the client is window对象 in node is the Global对象 first to say, look at the second one.

2.this when pointing to the object that called the function
function myObj() {    console.log(this.x); // 在这个例子里面是obj对象}var obj = {};obj.x = "xx";obj.myObj = myObj;obj.myObj(); // xx

The MyObj () function here refers to this obj, which is an externally passed object. Notice here in obj.myObj() front of Here obj. , because MyObj is the method of the Obj object, and the following obj calls the MyObj function as an object, so this is the object that points to the calling function.

3.this when you point to a new object generated by the constructor
// 作为构造函数的函数记得首字母要大写function People(gender) {     this.gender = gender;    this.sayGender = function() {        console.log(this.gender);    

Here's the implementation of the process, first of all, new People("man") this sentence did a few things:

  1. Create an empty object based on the constructor people{}
  2. And then passed into the people inside (this is called the beginning of the construction process, the meaning of the building blocks)
  3. And then the this in the function that starts here is a pointer to the new people{} object that was passed in.

Here is a simple process of building the constructor object, and you can simulate the following.

4.this points to objects that need to inherit attributes (apply and call)
function People(gender) {     this.gender = gender;    this.sayGender = function() {        console.log(this.gender);    }}var sally = new People("women");var bob = { // bob是直接量创建的,但是没有sayGender方法可以用    gender: "man";}

So how do you break it if Bob wants to use the sayGender() method? This time will be used apply() or call() , the two methods are similar.

  • Apply (obj, arguments) Here the arguments is a parameter array
  • Call (Obj,argument) there is no plural here

So if Bob is going to invoke sayGender() it, he'll have to use call() a method or apply() a method.

This can be understood as an inheritance, Java inheritance is divided into the implementation of inheritance and interface inheritance two, JavaScript inheritance is only the implementation of inheritance, but there are many implementations of the inherited JavaScript, such as the prototype chain inheritance, as well as here apply() and call() is also regarded as a kind of inheritance.

function People(gender) {     this.gender = gender;    this.sayGender = function(str) {        console.log(this.gender);    }}var sally = new People("women");var bob = { // bob是直接量创建的,但是没有sayGender方法可以用    gender: "man";}sally.sayGender("这是什么性别的?"); // 这是什么性别的?womensally.sayGender.call(bob,"这是什么性别的?"); // 这是什么性别的?man

Here's the last sentence of the code execution process under analysis:

  1. Pass Bob{gender: "Man"} This object into people
  2. Change function inside this point
  3. Continue executing the other code inside the function

As you can see, Bob, the object that inherits a method that inherits another object, can use this notationfunction.call(obj, argument)

At the same time can also know that this in the function of the point in fact there can be many kinds of, according to different circumstances to judge.

Let's start with an example of apply and get a basic understanding of the basics before you start apply() :

First of all popularize the next Concept class Array (array-like) , class array In fact we usually touch a lot of. Like the inside of a function, note that it's arguments对象 arguments对象 not arguments数组 . Because arguments is not an array but an object, we like to use such a notation when we usually use it, arguments[0] so it looks like an array. An array of classes is typically defined as an object that maintains a length property and can obtain an element based on a numeric subscript such as arguments[0] this.

If you don't believe it, we can test it:

function arrayLike() {    console.log(arguments instaceof Array); // false    console.log(arguments instaceof Object); // true}arrayLike();

In fact, the array object in JavaScript is called associative array , which is the form of key-value pairs in our database tables. So if you think JavaScript can optimize loops like in other languages like for(var i=0; i<100; i++) this process, you think much more.
Even JavaScript's internal implementations of objects are associative arrays , such as you can define objects with a key of 0 and a value other.

var obj = {    0: "12345"}var arr = ["12345"];console.log(obj[0]); // 12345console.log(arr[0]); // 12345

Do you think that the implementation of JavaScript inside is actually very simple? Or it can be said that the principle is basically one, but through a simple dot attribute subtraction attribute makes the object and the array look completely different. In fact, the internal realization principle is identical.

A bit more nonsense, here apply() 's an example of the method:

function People(gender) {     this.gender = gender;    this.sayGender = function() {        var str = Array.prototype.join.call(arguments,""); // arguments为类数组        console.log(str + this.gender); //     }}var sally = new People("women");var bob = {    gender: "man"}var textArr = "这是什么性别的?".split(""); // 这里将字符串分割为数组sally.sayGender.apply(bob, textArr); // 这是什么性别的?man

Probably come here, interested can leave a message to discuss.

Comparison of the use of this keyword in javascript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.