search
HomeWeb Front-endJS TutorialExploring what this pointer points to in JavaScript_Basic knowledge

Explore what this pointer points to in JavaScript

First of all, it must be said that the point of this cannot be determined when the function is defined. Only when the function is executed can it be determined who this points to. In fact, this ultimately points to the object that called it (this There are some problems with this sentence, and I will explain why there is a problem later. Although most articles on the Internet say this, although in many cases there will be no problems in understanding it that way, in fact, it is inaccurate to understand it that way, so There will be a feeling of uncertainty when you understand this), then I will explore this issue in depth next.

Why should you learn this? If you have studied functional programming or object-oriented programming, then you definitely know what it is used for. If you have not studied it, you don’t need to read this article for the time being. Of course, you can also read it if you are interested. After all, this is js. Something that must be mastered.

Example 1:

function a(){
  var user = "追梦子";
  console.log(this.user); //undefined
  console.log(this); //Window
}
a();

According to what we said above, this ultimately points to the object that calls it. The function a here is actually pointed out by the Window object, as the following code can prove.

function a(){
  var user = "追梦子";
  console.log(this.user); //undefined
  console.log(this);  //Window
}
window.a();

It’s the same as the above code. In fact, alert is also an attribute of window and is also clicked by window.

Example 2:

var o = {
  user:"追梦子",
  fn:function(){
    console.log(this.user); //追梦子
  }
}
o.fn();

This here points to the object o, because when you call this fn, it is executed through o.fn(), so the natural point is the object o. Let me emphasize again that the point of this cannot be determined when the function is created. Yes, it can be decided at the time of call. Whoever calls points to whom. Be sure to understand this.

In fact, Example 1 and Example 2 are not accurate enough. The following example can overturn the above theory.

If you want to fully understand this, you must read the next few examples

Example 3:

var o = { user:"追梦子", 
fn:function()
{ console.log(this.user); //追梦子 } } 
window.o.fn();

This code is almost the same as the code above, but why does this here not point to window? If according to the above theory, ultimately this points to the object that calls it. Here is an aside, window It is a global object in js. The variable we create actually adds attributes to the window, so we can use the window dot o object here.

Let’s not explain why this code in the above code does not point to window. Let’s look at a piece of code.

var o = {
  a:10,
  b:{
    a:12,
    fn:function(){
      console.log(this.a); //12
    }
  }
}
o.b.fn();

Object o is also pointed out here, but this also does not execute it. Then you will definitely say that what I said at the beginning is wrong? Actually it's not, it's just that what I said at the beginning was inaccurate. Next I will add a sentence. I believe you can completely understand the problem pointed by this.

Case 1: If there is this in a function, but it is not called by the upper-level object, then this points to window. What needs to be noted here is that in the strict version of js, this does not point to window, but We will not discuss the strict version here. If you want to know more, you can search online.

Case 2: If there is this in a function and this function is called by the upper-level object, then this points to the upper-level object.

Case 3: If there is this in a function, which contains multiple objects, even though the function is called by the outermost object, this only points to the object above it. Example 3 can prove , if you don’t believe it, then let’s continue to look at a few examples.

var o = {
  a:10,
  b:{
    // a:12,
    fn:function(){
      console.log(this.a); //undefined
    }
  }
}
o.b.fn();

Although there is no attribute a in object b, this this also points to object b, because this will only point to its upper-level object, regardless of whether there is something this wants in this object.

There is also a more special situation, Example 4:

var o = {
  a:10,
  b:{
    a:12,
    fn:function(){
      console.log(this.a); //undefined
      console.log(this); //window
    }
  }
}
var j = o.b.fn;
j();

This here points to window. Are you confused? In fact, it is because you did not understand a sentence, which is also crucial.

This always points to the object that called it last, that is, who called it when it was executed. In Example 4, although function fn is referenced by object b, it is not assigned when fn is assigned to variable j. It is not executed, so it ultimately points to window. This is different from Example 3, which directly executes fn.

This is actually the same thing, but it will point to something different in different situations. There are some small mistakes in the above summary, which cannot be said to be errors, but in different environments. The situation will be different next time, so I can't explain it clearly all at once. I can only let you experience it slowly.

Constructor version of this:

function Fn(){
  this.user = "追梦子";
}
var a = new Fn();
console.log(a.user); //追梦子

这里之所以对象a可以点出函数Fn里面的user是因为new关键字可以改变this的指向,将这个this指向对象a,为什么我说a是对象,因为用了new关键字就是创建一个对象实例,理解这句话可以想想我们的例子3,我们这里用变量a创建了一个Fn的实例(相当于复制了一份Fn到对象a里面),此时仅仅只是创建,并没有执行,而调用这个函数Fn的是对象a,那么this指向的自然是对象a,那么为什么对象Fn中会有user,因为你已经复制了一份Fn函数到对象a中,用了new关键字就等同于复制了一份。

除了上面的这些以外,我们还可以自行改变this的指向,关于自行改变this的指向请看JavaScript中call,apply,bind方法的总结这篇文章,详细的说明了我们如何手动更改this的指向。

更新一个小问题当this碰到return时

function fn() 
{ 
  this.user = '追梦子'; 
  return {}; 
}
var a = new fn; 
console.log(a.user); //undefined

再看一个

function fn() 
{ 
  this.user = '追梦子'; 
  return function(){};
}
var a = new fn; 
console.log(a.user); //undefined

再来

function fn() 
{ 
  this.user = '追梦子'; 
  return 1;
}
var a = new fn; 
console.log(a.user); //追梦子
function fn() 
{ 
  this.user = '追梦子'; 
  return undefined;
}
var a = new fn; 
console.log(a.user); //追梦子

什么意思呢?

如果返回值是一个对象,那么this指向的就是那个返回的对象,如果返回值不是一个对象那么this还是指向函数的实例。

function fn() 
{ 
  this.user = '追梦子'; 
  return undefined;
}
var a = new fn; 
console.log(a); //fn {user: "追梦子"}

还有一点就是虽然null也是对象,但是在这里this还是指向那个函数的实例,因为null比较特殊。

function fn() 
{ 
  this.user = '追梦子'; 
  return null;
}
var a = new fn; 
console.log(a.user); //追梦子

知识点补充:

1.在严格版中的默认的this不再是window,而是undefined。

2.new操作符会改变函数this的指向问题,虽然我们上面讲解过了,但是并没有深入的讨论这个问题,网上也很少说,所以在这里有必要说一下。

function fn(){
  this.num = 1;
}
var a = new fn();
console.log(a.num); //1

为什么this会指向a?首先new关键字会创建一个空的对象,然后会自动调用一个函数apply方法,将this指向这个空对象,这样的话函数内部的this就会被这个空的对象替代。

Statement
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
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.