Introduction
This plays a very important role in various object programming and is mainly used to point to the calling object. However, in JavaScript, the performance of this is very different, especially in different execution contexts.
From the previous article, we know that this is also an attribute in the execution context, so it is destined to be inseparable from the execution context.
activeExecutionContext = {
VO: {... },
this: thisValue};
In Javascript, the value of this depends on the calling mode. There are four calling modes: method calling mode, function calling mode, constructor calling mode and apply calling mode.
Call Pattern
Method Call Pattern
When a function is saved as a property of an object, we call it a method. When a method is called, this is bound to the object, that is, this in the method calling pattern points to the calling object. This is very easy to understand. You are a method of mine, you belong to me, and of course your this points to me.
var myObject = {
value : 0,
increment : function(inc) {
this.value = typeof inc === "number" ? inc : 1;
} }
}
myObject.increment();
console .log(myObject.value); //Output: 1
myObject.increment(3);
console.log(myObject.value); //Output: 4
Because you can access the object you belong to through this, you can call and modify the properties or methods in the object through it. As can be seen from the previous article, this, as a member of the attributes in the execution context, must be created when the context is created. All binding of this to the object occurs at the time of the call, which is a "delayed binding". A high degree of reuse of this can be achieved through delayed binding.
function showValue(){
console.log( this.value);
}
var a = { value : "a"};
var b = { value : "b"};
a.showValue = showValue;
b .showValue = showValue;
a.showValue(); //Output "a"
b.showValue(); //Output "b"
The function showValue in the above example belongs to delayed binding.
Function call mode
When a function is not called as a method of an object, it is a function call. In function calling mode, this is bound to the global object. (This is a mistake in language design)
myObject.double = function(){
var that = this; //Solution
var helper = function(){
console.log(that, ": ", that.value); //Output Object {value: 4, increment: function, double : function} ": " 4
console.log(this, ": ", this.value); //Output Window {top: Window, window: Window…} ": "
helper(); //Call
}
in function form
According to the normal thinking, as output in the fourth line, this should point to the object to which the function belongs. However, due to problems in language design, this points to the global object. This makes this even more mysterious and unpredictable. But as developers, this situation is definitely something we don’t want to see. It’s not common sense to play cards. Fortunately, the remedy is also very simple. In the above example, that is used to refer to this. In this way, calling that in the helper method can be used as this, which is simple and convenient. As for the function calling mode, why this behaves like this will be explained in detail later when analyzing the reference type.
Constructor calling mode
Since JavaScript is based on prototypal inheritance, its designers want it to be able to pass new and Constructors create objects, realizing object-oriented programming. This doesn't seem to be a good idea, and it's a bit embarrassing to draw a tiger instead of a dog. One is that it is impossible to learn, but there is no need to learn. JavaScript's prototypal inheritance mechanism is already very powerful, enough to meet the inheritance polymorphism required for object-oriented.
Without further ado, let’s talk about the constructor calling pattern. The constructor calling pattern is very simple. It is to use a function as a constructor, and then use this to introduce the properties and methods you intend to make public. As follows
function Person(name, age){
this .name = name;
this.age = age;
this.say = function(){
console.log("name : %s, age : %n", this.name, this. age);
}
}
var p1 = new Person("jink", 24);
p1.say(); //Output name : jink, age : 24
var p2 = new Person("Zhang San", 33);
p2.say();//Output name: Zhang San, age: 33
We can clearly see from the above example that this points to the object created through new and the constructor. Why is this happening? This is because when the constructor is called through new in JavaScript, the new operator calls the internal [[Construct]] method of the "Person" function, and then, after the object is created, the internal [[Call]] method is called. All the same function "Person" sets the value of this to the newly created object.
apply calling mode
After all functions in JavaScript are created, they will have two methods: apply and call. I don’t want to explain the specific use of these two methods in detail here. Students who don’t know can search on Baidu. It’s quite simple. Through two methods, we can set this manually. Although this is not allowed to be modified during creation, if we manually set it before creation, that is another matter. This setting is amazing, you can make your object call any method, just like you can make a car sail in the sea, an African elephant speed like a jaguar, and a programmer play like a pianist. Haha, imagination is always beautiful. Calling is calling, but whether the function can be realized after calling is another matter.
var programmer = {
name : "Programmer ",
hand : "Flexible hands",
program : function(){
console.log(this.name "Write code with " this.hand ".");
}
}
var pianist = {
name : "Pianist",
hand : "flexible hands",
play : function(){
console.log(this.name "Use" this.hand "Play beautiful music.");
}
}
var player = {
name : "athlete",
foot : "strong legs",
run : function(){
console.log(this.name "Use" this.foot "Race on the field.");
}
}
//Follow the rules
programmer.programme(); //Programmers write code with flexible hands.
pianist.play(); //The pianist uses his flexible hands to play beautiful music.
player.run(); //Athletes run on the field with strong legs.
//Whimsical
pianist.play.apply(programmer); //Programmers use their flexible hands to play beautiful music.
player.run.apply(programmer); //Programmer uses undefined to run on the field. Due to lack of exercise, I don’t have strong legs
The above looks interesting. The first parameter of apply is the this pointer in the execution method. In this way, we can borrow other people's methods and use them privately and secretly, which is extremely convenient. This type of technique is often used in some frameworks.
Summary
That’s all I have to say about this. I believe that after reading it, everyone will have some understanding of the judgment of this in different situations. I originally planned to discuss the next When discussing reference objects, I will explain the principle of this value in method calling mode and function calling mode. However, I am afraid that the length will be too long, so I decided to use a separate chapter to analyze the concept of reference objects.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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.


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

Dreamweaver CS6
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools