


About this keyword in javascript (translation self-understanding)_javascript skills
About 70% of the content below comes from http://www.quirksmode.org/js/this.html, and the other 30% is my own understanding and feelings about it. Hope it can be of some help to those in need. . .
First, let’s look at a very typical question about this keyword:
var name = 'hong'
var obj = {
name: 'ru',
getName: function(){
return function(){
return this.name;
};
}
}
alert(obj.getName()());
It’s not a big deal here, the execution result is :hong
Change the code slightly:
var name = 'hong'
var obj = {
name: 'ru',
getName: function(){
var that = this;
return function(){
return that .name;
};
}
}
alert(obj.getName()());
The execution result is: ru
The execution result is :ru
The reasons for this result will be discussed in detail below.
[Owner of function]
To explain this, we must first explain this concept. In JavaScript, this always points to the "owner" of the function we are currently executing. To be more precise: it points to the object that uses this function as a method.
How to understand this sentence, we can look at the following example:
/* -- test1 -- */
function test1 () {
this.title = 'me';
alert(window['title']);
alert (this === window); //true
}
test1();
The execution result is: me, true
In the above example, this It points to the window object. And write the title attribute of the window object as 'me'. Because test1 is a top-level function, its owner is the window object, or it is a method of the window object. This should not be difficult to understand. For example, when calling test1() above, it can also be written as window.test1(); which is clear.
Next, we create a div and assign test1 as a method to the onclick attribute of the div:
The result of clicking the div is: undefined, false; At the same time, we can use firebug to see that the attribute value of 'me' is actually assigned to the one with the id of 'o' HtmlObject

Obviously, this points to the div at this time, that is to say, the owner of test1() becomes the HtmlObject of the div, or it becomes the onclick method of the div to call. This situation should still be easy to understand.
Next we will change the code, just change one place:
o.onclick = test1(); // Note: A bracket is added here
After changing the last sentence of the above code to this, the result of clicking the div is: me, true
It becomes the same as the first situation, this points to the window. Some people may wonder and think there is no difference, but in fact there is. This involves the issue of copy and refer functions.
【Copy of function】
If you copy the code through
o.onclick = test1;
In this way, the function test1() is actually copied to the onclick attribute of object o. Therefore, the owner of test1 becomes the o object.
If you copy the code through
o.onclick = test1() ;
In this way, it essentially means that when the handle of the click event is obtained, it is directed to execute the test1() function. Note that it guides execution rather than assigning it to execution. The owner of test1() has not changed, it is still window.
[Refer of function]
Same as above, if we write the call inline to HTML and call it, it is still the refer method
The execution result of clicking the div still indicates that this points to the window.
[Example of function copy]
element.onclick = doSomething
element.addEventListener('click',doSomething,false)
element.onclick = function () {this.style.color = '#cc0000';}
These methods will change the pointer of this to the currently called object.
[Example of function refer]
element.onclick = function () {doSomething()}
element.attachEvent('onclick',doSomething)
These methods It will not change the owner of the function. It should be noted that addEventListener and attachEvent are inconsistent, because attachEvent actually establishes a reference to doSomething instead of copying the function.
[Use the call method]
As we just said, writing
function (o) {
o.title = 'me';
}
Such an explicit call is OK. Alternatively, you can use call or apply to impersonate inheritance methods
function test () {
this.title = 'me';
}
This is also the most typical way of object impersonation.
[Free variable problem]
After writing this long, let’s go back to the original question:
var name = 'hong'
var obj = {
name: 'ru',
getName: function(){
return function(){
return this.name;
};
}
}
alert(obj.getName()());
Why does the result obtained in this way be: hong? The focus is on
return function(){
return this .name;
};
Comparing the function refer example written above, it is not difficult to find that the calling method of the returned anonymous function is the same as onclick = function () {doSomething()} same. So this method does not change the owner of this function. Although it is a nested function, its declaration is top-level. Among them, this points to window.
The second way is to force this to be assigned to that in getName(), that is to say, that.name is actually the same as this.name in getName(). In the context of getName, its owner is the object obj, so this will point to obj, so this.name === obj.name;
I have gone through such a big circle, but I don’t know if I have made it clear to you. .
In fact, it can be summarized like this: In the function context where this is located, if this function is not called in the form of a "method", then this will point to the window object, otherwise it will point to the owner of this function.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

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.

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

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 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 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.

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.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft