The Chinese meaning of this is "current; this". It is a pointer variable in JavaScript, which points to the running environment of the current function. When the same function is called in different scenarios, the pointer of this will change, but it will always point to the real caller of the function in which it is located; if there is no caller, this will point to the window.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript The scope of a function is static, but the function call is dynamic. Since functions can be executed in different running environments, JavaScript defines the this keyword in the function body to obtain the current running environment.
this is a pointer variable that points to the running environment of the current function.
When the same function is called in different scenarios, the pointer of this may also change, but it will always point to the real caller of the function in which it is located (whoever calls it points to who); if there is no caller, this Just point to the global object window.
Use this
This is automatically generated by the JavaScript engine when executing the function. It is a dynamic pointer that exists within the function and refers to the current calling object. The specific usage is as follows:
this[.属性]
If this does not contain attributes, the current object is passed.
This is flexible in usage and the values it contains are also varied. For example, the following example uses the call() method to continuously change the object this refers to within a function.
var x = "window"; //定义全局变量x,初始化字符串为“window” function a () { //定义构造函数a this.x = "a"; //定义私有属性x,初始化字符a } function b () { //定义构造函数b this.x = "b"; //定义私有属性x,初始化为字符b } function c () { //定义普通函数,提示变量x的值 console.log(x); } function f () { //定义普通函数,提示this包含的x的值 console.log(this.x); } f(); //返回字符串“window”,this指向window对象 f.call(window); //返回字符串“window”,指向window对象 f.call(new a()); //返回字符a,this指向函数a的实例 f.call(new b()); //返回字符b,this指向函数b的实例 f.call(c); //返回undefined,this指向函数c对象
The following is a brief summary of the performance and response strategies of this in 5 common scenarios.
1. Ordinary calls
The following example demonstrates the impact of function references and function calls on this.
var obj = { //父对象 name : "父对象obj", func : function () { return this; } } obj.sub_obj = { //子对象 name : "子对象sub_obj", func : obj.func } var who = obj.sub_obj.func(); console.log(who.name); //返回“子对象sub_obj”,说明this代表sub_obj
If you change the func of the sub-object sub_obj to a function call.
obj.sub_obj = { name : "子对象sub_obj", func : obj.func() //调用父对象obj的方法func }
Then this in the function represents the parent object obj where the function is defined.
var who = obj.sub_obj.func; console.log(who.name); //返回“父对象obj”,说明this代表父对象obj
2. Instantiation
When calling a function using the new command, this always refers to the instance object.
var obj = {}; obj.func = function () { if (this == obj) console.log("this = obj"); else if (this == window) console.log("this = window"); else if (this.contructor == arguments.callee) console.log("this = 实例对象"); } new obj.func; //实例化
3. Dynamic calling
Use call and apply to force this to point to the parameter object.
function func () { //如果this的构造函数等于当前函数,则表示this为实例对象 if (this.contructor == arguments.callee) console.log("this = 实例对象"); //如果this等于window,则表示this为window对象 else if (this == window) console.log("this = window对象"); //如果this为其他对象,则表示this为其他对象 else console.log("this == 其他对象 \n this.constructor =" + this.constructor); } func(); //this指向window对象 new func(); //this指向实例对象 cunc.call(1); //this指向数值对象
In the above example, when func() is called directly, this represents the window object. When a function is called using the new command, a new instance object will be created, and this will point to this newly created instance object.
When using the call() method to execute the function func(), since the parameter value of the call() method is the number 1, the JavaScript engine will force the number 1 to be encapsulated into a numerical object, and this will point to this Numeric object.
4. Event processing
In the summary of event processing functions, this always points to the object that triggered the event.
<input type="button" value="测试按钮" /> <script> var button = document.getElementsByTagName("put")[0]; var obj = {}; obj.func = function () { if (this == obj) console.log("this = obj"); if (this == window) console.log("this = window"); if (this == button) console.log("this = button"); } button.onclick = obj.func; </script>
In the above code, this contained in func() no longer points to the object obj, but to the button button, because func() is called after being passed to the button's event handling function. .
If you use the DOM2 level standard to register the event handler function, the procedure is as follows:
if (window.attachEvent) { //兼容IE模型 button.attachEvent("onclick", obj.func); } else { //兼容DOM标准模型 button.addEventListener("click", obj.func, true); }
In the IE browser, this points to the window object and button object, but in the DOM standard browser it only points to button object. Because, in the IE browser, attachEvent() is a method of the window object. When this method is called, this will point to the window object.
In order to solve browser compatibility issues, you can call the call() or apply() method to force the method func() to be executed on the object obj to avoid the problem of different browsers parsing this differently.
if (window.attachEvent) { button.attachEvent("onclick", function () { //用闭包封装call()方法强制执行func() obj.func.call(obj); }); } else { button.attachEventListener("onclick", function () { obj.func.call(obj); }, true); }
When executed again, this contained in func() always points to the object obj.
5. Timer
Use the timer to call the function.
var obj = {}; obj.func = function () { if (this == obj) console.log("this = obj"); else if (this == window) console.log("this = window对象"); else if (this.constructor == arguments.callee) console.log("this = 实例对象"); else console.log("this == 其他对象 \n this.constructor =" + this.constructor); } setTimeOut(obj.func, 100);
In IE, this points to the window object and button object. The specific reason is the same as the attachEvent() method explained above. In DOM-compliant browsers, this points to the window object, not the button object.
Because the method setTimeOut() is executed in the global scope, this points to the window object. To resolve browser compatibility issues, you can use the call or apply methods.
setTimeOut (function () { obj.func.call(obj); }, 100);
【Related recommendations: javascript learning tutorial】
The above is the detailed content of What does this mean in javascript. For more information, please follow other related articles on the PHP Chinese website!

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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),

Zend Studio 13.0.1
Powerful PHP integrated development environment

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.