Home Web Front-end JS Tutorial A brief introduction to Javascript: this_Basic knowledge

A brief introduction to Javascript: this_Basic knowledge

May 16, 2016 pm 05:08 PM
javascript this

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.

Copy code The code is as follows:

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.

Copy code The code is as follows:

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.

Copy code The code is as follows:

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)

Copy code The code is as follows:

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

Copy code The code is 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.

Copy code The code is as follows:

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.

Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles