Example tutorial on the usage of This in javascript
I have read the book "JavaScript You Don't Know" several times. It seems that every time I read it, I make new discoveries. Some of the content cannot be understood at once, but I seem to understand some concepts every time I read it.
Reread the this
keyword again. The concept is very flexible and very difficult to grasp, so I see no harm in reading it often. I hope that JavaScript will be popular in the world, so the cost of learning will be low!
Refer to Chapter 1 and Chapter 2 of the second part of this book.
This keyword is one of the most complex mechanisms in js. It is automatically defined in the scope of all functions.
It seems that I also took a long detour in the process of learning this keyword. You have to ask me why I took a long detour. The key point is that I still haven’t thoroughly learned and understood the core concepts. This is no different from primary school students learning new knowledge. If you want to master the keyword this, you need to stick to the key concepts and don't imagine what this is all about.
Key concept: When a function in js is called, it must, must, be bound to an object. When analyzing the this keyword, you must know what the object is when the function is called. who is it? .
Remember: There is no relationship between the call and the definition of a function in js. The object bound to the function cannot be known until it is called.
The uncertainty of this keyword is a double-edged sword. One is the uncertainty of the object when the function is called. The use of functions in js is very flexible. Each object can borrow other functions. to complete the function. Second, this also caused some problems in learning this. So when learning, you must first understand the advantages of this keyword, and then go to learn the places that cause trouble
First look at the first piece of code
page 75
//注意只是定义了一个函数,并未调用,这时候函数是没有绑定任何对象function identify() {return this.name.toUpperCase(); }//同上面的函数,但是这个函数内部有点复杂,如果下面的代码看不懂//可以只看上面的函数function speak() {var greeting = "Hello, I'm " + identify.call( this );console.log( greeting ); }var me = { //定义了一个字面量对象 name: "Kyle" };var you = {//定义了一个字面量对象 name: "Reader" };//通过call方式把函数identify分别绑定到两个对象上//这时的this是指向me对象,和you对象 identify.call( me ); // KYLE identify.call( you ); // READER//通过call方式把函数call分别绑定到两个对象上//这时的this是指向me对象,和you对象 speak.call( me ); // Hello, I'm KYLE speak.call( you ); // Hello, I'm READER
When defining a function in JavaScript, the function does not belong to any object. This is very critical, very critical, very critical. This is the first obstacle to understanding this keyword.
The uncertainty of this keyword when defining js functions makes the use of js functions extremely flexible, and any object can use it.
What is this?
The binding of this has nothing to do with the location of the function definition, it only depends on the way the function is called
.
When a function is called in javascript, an activity will be created Record (sometimes called context). This record includes where the function was called, the calling method of the function, and the parameters passed in. this is an attribute in the record.
The first problem when learning javascript keywords is to solve how to know the calling position of the function.
binding. This is the largest concept that needs to be mastered after understanding the difference between the definition and calling of js functions. There are four binding methods in js. Personally speaking, binding rules is not difficult,
The difficulty lies in understanding the function scope of js. Especially
default binding. This binding method is extremely confusing.
Look at the code below page 83
function foo() { //这是函数的定义位置console.log( this.a ); } var a = 2;//这个变量定义的含义是什么呢?仅仅是赋值给a吗? foo(); // 2 //这是函数的调用位置。为什么会打印出2呢?
Many functions are called like this. You can also write them in a similar way, but it is different if you understand the specific meaning.When we use the setTimeout and setInterval functions, these two functions are actually naked and are also bound to the window object. Implicit bindingThe function has modifiers added when it is called. Look at the code belowThe foo function is defined in the global scope (window scope). Coincidentally, its call is also in the global scope. Note that this is just a coincidence. So why does the value of variable a print out when foo() is called? Although the keyword var is used, we can know from the scope analysis that the variable a is actually a global variable. To put it more clearly, a is actually an attribute of the global object window, and 2 is the attribute value of this attribute.
When foo() is called, it is completely naked. It is just the function itself without any modifiers. At this time, it does not have any function wrapper and is under the global scope, so this in foo() points to For global objects, when you want to print this.a, you will find the global scope when you look for the call location of foo(). When you look for the attribute this.a of the global scope, you will print out the attribute value 2.
page 85
function foo() { //定义在全局作用下的函数,仅仅是定义,不是调用位置console.log( this.a ); }var obj = { //定义一个对象 a: 2,foo: foo }; obj.foo(); // 2 给foo()函数找了一个对象,this就指向这个对象了
Implicit lossYou often see the sentence
var that=this; //这是什么含义
看下面段代码.这段代码其实以前我也不太理解,问题还是没有彻底领悟js函数定义和调用之间是没有关系的这一点。
page 86
function foo() { //定义了一个函数console.log( this.a ); }var obj = { //定义了一个对象字面量 a: 2,foo: foo //函数作为对对象的属性 };var bar = obj.foo; //把obj对象的函数foo属性赋值给bar变量//这里就是理解这个问题的关键,如果你现在认为调用bar()的时候绑定的对象//是obj那就完全搞错了。这个时候仅仅是把函数foo赋值给了var变量,//并没有把对象也给bar变量,因为这里还不是foo()函数的调用位置,现在//foo函数还没有绑定对象,那么调用bar()的时候对象到底是谁?不知道。//调用的时候才知道。var a = "oops, global"; // 任然是全局对象的属性 bar(); // "oops, global" 这里执行的是默认绑定,this就是去全局对象啦
下面这段代码就是使用var that=this的场景
在使用回调函数的时候要留心。js中函数是一等对象,可以作为另一个函数的参数传入函数。 问题就出在这里了,函数一旦作为实参代替形参的时候,实际也执行了和上面代码一样的赋值过程,实际只是传递了函数本身,原先的对象就没有了。
page 86
function foo() { //定义一个函数console.log( this.a ); }function doFoo(fn) { //fn是形参// 如果函数作为实参传入相当于代码 var fn=obj.foo//和上面一段代码是完全一样的,只是函数本身,并没有绑定任何对象 fn(); // 在这里调用的时候,由于fn只代表foo()函数,被绑定到全局对象上了 }var obj = {a: 2,foo: foo };var a = "oops, global"; // `a` also property on global object doFoo( obj.foo ); // "oops, global"不要被obj.foo迷惑了//没有实际执行函数的调用,此时obj.foo仅仅代表没有绑定任何对象的函数//这个代码块看着眼熟么?这就是javascript中回调函数的样子,当//一个函数作为参数传递进另一个函数的时候,这个参数函数就找不到自己绑定的对象是谁了,//所以就默认绑定到全局对象上了。但是我们既然在一个函数里调用另一个函数,肯定是要用这个函数操作当前的对象,那么既然找不到了,我们就手动给他指定一个对象吧。这就是为什么要使用//var that=this的原因。我觉得理解这个概念,js的功力至少会增加5%
The above is the detailed content of Example tutorial on the usage of This in javascript. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



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.

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

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

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

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

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

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
