JavaScript Basic Practice (2)--what's This (top)
The developer's JavaScript attainments depend on the level of understanding of the two words "dynamic" and "asynchronous".
[TOC]
I. What is this?
this
is one of the JavaScript keywords and is the core concept that JavaScript can implement object-oriented programming . Use well can let code elegant high-end, coquettish elegant, with bad also is absolutely deceptive pit own weapon. We often see in some materials that the this
descriptions are:
this
is a special execution contexts -related object used to indicate the execution contextsof the current code execution, this
in which statement execution enters a execution Contexts is assigned and cannot be changed during code execution.
Note:execution Contexts is the "context" or "execution Environment"that we often hear.
Can't you read it? If you don't understand it, I can't read it.
For this
the point, we often hear a principle-thisis a pointer to the object that is currently calling it . But in practice, we find it sometimes difficult to know which object is currently being invoked , which leads to a series of misuse and strange phenomena.
Today, let's take a different approach and try to understand it from a language perspective this
, and you'll find:
As long as you understand Chinese, it means you can understand this.
Two. The grammatical significance of this2.1 this at close range
JavaScript is a programming language , that is, it is a language , is a language, there are grammatical characteristics. If the principle of throwing away this
and the use of programming, only from the language level to understand, its essence is 代词
. What is a pronoun? In Chinese,,,, 你
我
他
你们
我们
他们
This kind of word is a pronoun. A pronoun does not specifically refer to a specific thing, but in combination with the context, it is possible to know who the word is instead.
For example, the following sentence describes the context:
- his Big uncle is Zhao Benshan
- Excuse me: Who is Uncle Zhao?
- Unable to answer, because there is no context constraint, He may refer to anyone here.
- Li Lei's story is not small, his uncle is Zhao Benshan
- Excuse me: Who is Uncle Zhao?
- It is easy to answer, because the previous sentence allows us to know that in the current context,"he" refers to "Li Lei".
- ___ is not small, his Big uncle is Zhao Benshan
- Excuse me: Who is Uncle Zhao?
- Here is the space to fill who, who Uncle Zhao Benshan.
Summary:
Pronouns are used to refer to a specific thing, and when the context is combined, it is possible to know its specific point. In other words, a pronoun has a specific meaning when it is in context. The meaning in the this
JavaScript language 代词
is the same as in Chinese.
2.2 This in different scopes
Before the advent of ES6, the scopes in JavaScript were divided into global scope and function scope. (Strict mode is not discussed in the following sections).
The global scope this
is pointing window对象
, but it window对象
does not have this
this property:
The function scope is this
also pointed (pointing in this example window对象
), we know that the function of the prototype chain is pointed Object
, so the function itself can be treated as an object, but unfortunately the 函数
prototype chain does not have this
this attribute:
In summary, it this
can be intuitively understood as:
This is related to a function, which is a local constant that is automatically assigned to a function at run time by the interpreter.
2.3 How JavaScript code is written
A. Do not this
use
It is possible that this will happen. Many beginners will find that they do not use this when writing JavaScript code, but it does not affect their own coding. The meaning of the context information mentioned earlier is that the pronoun is clearly pointed, so if the pronoun is not used in the context of a paragraph, we do not need to contact the context to understand the phrase in the language, and similarly, if the function body does not use the this
keyword to refer to any object, Or if you don't need to focus on the calling object, the this
execution of the function will not be ambiguous, even if you are unsure of the point.
/** *数据加工转换类的函数,对开发者来说更关注结果,而并不在乎是谁在调用。*/function addNumber(a,b) { return a + b;}
Whether the computer object calls the Addnumber method, or the Abacus object calls the Addnumber method, even the human object is called by mental arithmetic Addnumber method, it doesn't matter, because we focus on the result, not how it comes.
B. Do not use functions that bring this
their own
Sometimes we write code that requires some information about it 调用对象
, but because of unfamiliar this
usage, many developers use another alternative, namely, explicit arguments . For example, in a method, the name of the context object needs to be typed, and the following two ways of writing are achievable.
//方式一.使用thisinvoker.whoInvokeMe = function(){ console.log(this.name);}//方式二.不使用thisfunction whoInvokeMe2(invoker){ console.log(invoker.name);}
The way two is not a grammatical error, allowing developers to avoid the confusion caused by the misuse of the keyword, but also to avoid the resulting this
this
abstraction and simplicity of the code, while causing some performance loss, After all, doing so will require more arguments to be processed each time the function is called, and these parameters can be obtained through the built-in this
.
C. Object-oriented Programming
The mention of this will inevitably refer to another term- object oriented . "Object-oriented" is a programming idea, please temporarily cast off the package , inheritance , polymorphism and other high-level modifiers brought about the burden, purely to feel the thought itself. Some people say that "object-oriented" gives programming a philosophical meaning, it is a simplified abstraction of the real world in the way of program language, a user of the real world, a strategy, a message, an algorithm, which is regarded as an object in the object-oriented world, in the philosophical sense 无分别
, Every object has its life cycle, how it comes, what it does, how it dies, and how it relates to everything.
面向对象
Idea, which is one of the ways of outlining the real-world framework in programming language, is not designed to embarrass developers, but to enable developers to improve their understanding of the programming language in a way that is closer to everyday life.
2.4 If there is no this
Let's take a look. If you don't use keywords in javascript this
, what's the impact on programming?
Let's start by writing a simple definition code:
//假设我们定义一个人的类 function Person(name){ } // 方法-介绍你自己(使用this编写) Person.prototype.introduceYourselfWithThis = function () { if (Object.hasOwnProperty.call(this, ‘name‘)) { return `My name is ${this.name}`; } return `I have no name`; } // 方法-介绍你自己(不使用this编写) Person.prototype.introduceYourself = function (invoker) { if (Object.hasOwnProperty.call(invoker, ‘name‘)) { return `My name is ${invoker.name}`; } return `I have no name`; } //生成两个实例,并为各自的name属性赋值 var liLei = new Person(); liLei.name = ‘liLei‘; var hanMeiMei = new Person(); hanMeiMei.name = ‘hanMeiMei‘;
In the simple example above, we define a class that does not contain any instance properties, 人
and introduce you to this method in a different way for its definition, the first of which uses the general object-oriented approach, using the this
get context object, to get the properties of the instance name
; this
instead of using the second definition, the caller name is passed as a parameter into the method.
We make some simple use of the console:
So what is the difference between these two different ways of writing?
-
function changes in actual functionality
It is not difficult to see from the above example that when this is not used in development, the developer is required to pass in the context object itself and pass it in as a parameter when the function executes, if the incoming Invoker the object and This are aligned, the results are consistent and, if inconsistent, cause confusion.
- from the encoding point of view
Introduceyourselfwiththis ()
method just introduceyourself (invoker)
A special case of the method (when this = = = Invoker).
- writes the introduceyourself ()
method from the meaning of the method
the definition wants to implement self-introduction
, but the user reads to Introduceyourself () The source code of the
to see the meaning is: I tell you a name, you fill it in the words ' My name is __ ' and return to me. instead of a self-introduction action that is closely related to the calling object.
-
parameter passing for superfluous parameters
The point of this and Invoker is consistent during proper use, formal parameters The definition of Invoker not only increases the complexity of function usage, but also increases the burden of function operation, but does not bring any new additional information to the execution of the function.
- Duplicate code
If you do not use this
in your encoding, it is equivalent to not using pronouns in Chinese, then we need to use complete information in each individual sentence. In order for the introduceyourself ()
method to execute correctly, we need to bind the exact instance method to each instance after it is generated, namely:
var liLei = new Person(); liLei.name = ‘liLei‘; //定义实例方法 liLei.introduceYourself = function (){ return `My name is liLei`; }; var hanMeiMei = new Person(); hanMeiMei.name = ‘hanMeiMei‘; //定义实例方法 hanMeiMei.introduceYourself = function (){ return `My name is hanMeiMei`; }
If you don't use it immediately this
, you won't be directly stuck in a situation where you can't write JavaScript code, you just need to externalize all of your definitions and usage scenarios, and you'll need to manually write a concrete implementation of all the specific features, namely "process-oriented" programming.
================================ I'm gorgeous split-line ======================================
"Relaxing Moment"
Words Chibi after the war, a day idle to Nothing, Hung Ming and Liu closed three brothers drink together. Hung Ming said, I have three questions to test your knowledge accomplishment, how AH? The three brothers raised their hands to agree.
Hung Ming: The first question, my Lord, where is the Battle of Chibi?
Liu Bei: Chibi Ah
Hung Ming: Correct, my lord is really bad. The second question, general, how many people on both sides of the war?
Guan Yu: Coalition 50,000, Cao June more than 200,000.
Hung Ming: Correct, General is also are strong AH. The last question, who are they respectively?
Zhang Fei: i ... Holy
May you be able to master this
, do not in your own code to find out who their differences are embarrassing, careful to be buried alive by teammates.
================================ I'm gorgeous split-line ======================================
Three. General direction rules for this
There are four this
basic rules for pointing in JavaScript. Today, we will read these rules separately through the "Code farming perspective " and "language teacher Perspective ", and you will find that they are naturally understood.
When the rule is called as a function call, this points to the global object
A global object in a browser that refers to an window
object. This rule refers to a function that we create in a global scope or function scope that uses a function
keyword to directly declare or use a function expression to assign a value to an identifier. In order to find the declared method in memory at the time of invocation, we need an identifier to point to its location, the named function can be found by its name, and the anonymous function needs to be found by the identifier. the essence of a function call is to find the function and execute it by means of a method name straight or an identifier.
What kind of functions do we define in general?
Are those that do not care about callers, such as the Addnumber () method above, which often combines one or more steps of business logic to make a new name easier to manage and reuse, without paying attention to who the user is.
Chinese Teacher interpretation version :
It's good to understand that when you want to describe an action but don't know or care about who did it, the pronoun points to it 有的人
.
For example, Zang Kejia's classmates wrote in the composition of this:
Some people live, but he is dead;
Some people are dead, but he is still alive;
Who is he referring to in the above? Who are those people ? Whatever, love who.
When Rule 2--is called as a method, this points to the context object
In the above we see that the scope of the function is contained in the chain Object
, so the function can be understood as an object. When a function is assigned to another object's property as an object, the address of the function is saved in the property value of the object, because the function is assigned the value of a reference type when it is the right value of the assignment operation. If this function is exactly another anonymous function, then execution can only be performed by locating the function in memory using the address information recorded in the object's properties . So when a function is called as a method, the nature of the this
information contained in it is how the function is searched for when it executes. The answer is: found by the properties of this object pointed to by this.
What kind of functions do we define in general?
A function defined as a method is often a concrete implementation of another abstract collection. For example addNumber()
, this method, which simply adds two numbers to an abstract action, does not matter who is performing the computational process by what means, it can summarize all the objects add two numbers and give the result of the action. But if it is invoked as an object method, there is a clearer sense of reality pointing to it:
Computer.addNumber()
It expresses the process of the computer to give the result through the combination of hardware and software.
Calculator.addNumber()
The process by which the calculator gives results through simple hardware calculations
Abacus.addNumber()
The process by which the abacus is given the result by adding and reducing beads
- ...
Chinese Teacher interpretation version :
When you want to know who a pronoun refers to, of course, you need to contact context to understand it.
When Rule 3--is used as a constructor, this points to the generated instance
Used as a constructor, is the case where the new + constructor function name is called.
The logic of the JS engine calling the new operator can be represented by pseudo-code:
new Person(‘liLei‘) = { //生成一个新的空对象 var obj = {}; //空对象的原型链指向构造函数的原型对象 obj.__proto__ = Person.prototype; //使用call方法执行构造函数并显式指定上下文对象为新生成的obj对象 var result = Person.call(obj,"liLei"); // 如果构造函数调用后返回一个对象,就return这个对象,否则return新生成的obj对象 return typeof result === ‘object‘? result : obj;}
Without considering the return value of the constructor, it is easy to see why it is this
pointing to the instance, because the class definition function explicitly binds this to the 新生成的对象
instance object that was obtained after invoking the new operator at execution time.
Chinese Teacher interpretation version :
Some students like plagiarism, plagiarism this action can be described as: "Copy a copy of the job, in the end to write their own name." "。 If Li Lei is one of the people who like plagiarism , then he has mastered the "plagiarism" method, then you think he finished the homework in the signature place should write his name "Li Lei" or write this category of people collectively "like plagiarism"?
The classmate of contradicting, I remember you! Don't go after school!
Rule 4--explicitly specify this using the Call/apply/bind method
call
/ bind
/ apply
These three methods are an important part of the dynamic nature of JavaScript, and the subsequent chapters will be explained in detail. Just look at the API usage and see how it affects this point:
- Func.call (This, arg1, arg2 ...)
- Func.apply (This, [Arg1, arg2 ...])
- Func.bind ( This [, arg1[, arg2[, ...])
This rule is well understood, that is, when the function executes, it encounters this
statements in the body of the function that are replaced with explicitly specified objects.
Chinese Teacher interpretation version :
is to tell you directly what the pronoun in the following refers to, for example: XXX Constitution (hereinafter referred to as "this Law"), the reader is of course aware of the following "This law" refers to WHO.
Four. Basic rule examples
To see the difference between the above two principles more clearly, let's look at an example:
var heroIdentity = ‘[Function Version]Iron Man‘; function checkIdentity(){ return this.heroIdentity; } var obj = { name:‘Tony Stark‘, heroIdentity:‘[Method Version]Iron Man‘, checkIdentityFromObj:checkIdentity } function TheAvenger(name){ this.heroIdentity = name; this.checkIdentityFromNew = checkIdentity; } var tony = new TheAvenger(‘[New Verison]Iron Man‘); console.log(‘1.直接调用方法时结果为:‘,checkIdentity()); console.log(‘2.通过obj.checkIdentityFromObj调用同一个方法结果为:‘,obj.checkIdentityFromObj()); console.log(‘3.new操作符生成的对象:‘,tony.checkIdentityFromNew()); console.log(‘4.call方法显示修改this指向:‘,checkIdentity.call({heroIdentity:‘[Call Version]Iron Man‘}));
The result of the console output is this:
The same method , the same this, is called in a different way, and the results are different.
Five. PostScript
In front of the foundation, all skills are floating clouds.
If you think you can do whatever you like by knowing the basic rules of this, you really too young too .
Understanding the basic Point rules only allows you to dig as little as possible or not to dig holes in your development. But it takes more discipline and reflection to fill someone's hole or read the simple and elegant usage of master code. Many of the complex usage scenarios in practical applications are difficult to figure out this
at once and why to specify the point of this.
The author will be in the "Basic JavaScript (3)--what ' s This (next)" in detail about the development of strange this
. Want to know how to funeral, first order a praise first!
Reference article:
[What's New in 1].js ()
[2]. Ecma-262-3 in detail. Chapter 1. Execution contexts
JavaScript Basic Practice (2)--what's This (top)