当前位置:网站首页>This point in JS
This point in JS
2022-06-30 08:14:00 【Front lvxiaobu】
meaning
this Can be used in constructors , Represents an instance object . besides ,this It can also be used in other occasions . But whatever the occasion ,this All have one thing in common : It always returns an object .
In short ,this Property or method “ At present ” Where you are .
this.property in this On behalf of property Property is the current object .
var person = {
name: ' Zhang San ',
describe: function () {
return ' full name :'+ this.name;
}
};
person.describe()
// " full name : Zhang San "
In the above code ,this.name Express name The object where the property is located . because this.name Is in describe Call in method , and describe The current object of the method is person, therefore this Point to person,this.name Namely person.name.
Because the properties of an object can be assigned to another object , So the current object where the attribute is located is variable , namely this The direction of is variable .
var A = {
name: ' Zhang San ',
describe: function () {
return ' full name :'+ this.name;
}
};
var B = {
name: ' Li Si '
};
B.describe = A.describe;
B.describe()
// " full name : Li Si "
In the above code ,A.describe Attribute is assigned to B, therefore B.describe It means describe The current object of the method is B, therefore this.name Point to B.name.
Refactor this example a little ,this The dynamic direction of can be seen more clearly .
function f() {
return ' full name :'+ this.name;
}
var A = {
name: ' Zhang San ',
describe: f
};
var B = {
name: ' Li Si ',
describe: f
};
A.describe() // " full name : Zhang San "
B.describe() // " full name : Li Si "
In the above code , function f Internal use this keyword , With f The object is different ,this The direction is also different .
As long as the function is assigned to another variable ,this The direction of will change .
var A = {
name: ' Zhang San ',
describe: function () {
return ' full name :'+ this.name;
}
};
var name = ' Li Si ';
var f = A.describe;
f() // " full name : Li Si "
In the above code ,A.describe Is assigned to a variable f, Inside this Can point to f The object on which the runtime resides ( This example is a top-level object ).
To sum up ,JavaScript In language , Everything is the object , The running environment is also an object , So all functions run in an object ,this Is the object where the function runs ( Environmental Science ). This would not have confused users , however JavaScript Support dynamic switching of operating environment , in other words ,this The direction of is dynamic , There is no way to determine in advance which object to point to , This is the most confusing place for beginners .
principle
JavaScript The reason why language has this The design of the , It has something to do with the data structure in memory .
var obj = {
foo: 5 };
The above code assigns an object to a variable obj.JavaScript The engine will be in memory first , Generate an object { foo: 5 }, Then assign the memory address of the object to the variable obj. in other words , Variable obj It's an address (reference). If you want to read later obj.foo, The engine starts with obj Get the memory address , Then read the original object from the address , Back to its foo attribute .
The original object is stored in a dictionary structure , Each attribute name corresponds to an attribute description object . for instance , In the example above foo attribute , It is actually saved in the following form .
{
foo: {
[[value]]: 5
[[writable]]: true
[[enumerable]]: true
[[configurable]]: true
}
}
Be careful ,foo The value of the property is stored in the value Attributes inside .
This structure is very clear , The problem is that the value of the property may be a function .
var obj = {
foo: function () {
} };
At this time , The engine will store the function in memory separately , Then assign the address of the function to foo Attribute value attribute .
{
foo: {
[[value]]: Address of function
...
}
}
Because the function is a single value , So it can be in different environments ( Context ) perform .
var f = function () {
};
var obj = {
f: f };
// Perform alone
f()
// obj Environmental execution
obj.f()
JavaScript Allow inside function body , Reference other variables of the current environment .
var f = function () {
console.log(x);
};
In the above code , Variables are used in the function body x. This variable is provided by the runtime environment .
Now the question is , Because functions can be executed in different environments , So there needs to be a mechanism , Can get the current running environment inside the function body (context). therefore ,this And that's what happened , It's designed to be inside the function body , Refers to the current running environment of the function .
var f = function () {
console.log(this.x);
}
In the above code , In the function body this.x It refers to the current operating environment x.
var f = function () {
console.log(this.x);
}
var x = 1;
var obj = {
f: f,
x: 2,
};
// Perform alone
f() // 1
// obj Environmental execution
obj.f() // 2
In the above code , function f Execute... In a global environment ,this.x Pointing to the global environment x; stay obj Environmental execution ,this.x Point to obj.x.
Use scenarios
this It is mainly used in the following occasions .
(1) Global environment
Global environment usage this, It refers to the top-level object window.
this === window // true
function f() {
console.log(this === window);
}
f() // true
The above code shows , Whether inside the function or not , As long as it runs in a global environment ,this It refers to the top-level object window.
(2) Constructors
In the constructor this, Refers to the instance object .
var Obj = function (p) {
this.p = p;
};
The above code defines a constructor Obj. because this Point to instance object , So define inside the constructor this.p, It is equivalent to defining that the instance object has a p attribute .
var o = new Obj('Hello World!');
o.p // "Hello World!"
(3) Object method
If the method of the object contains this,this The point of is the object where the method runs . This method is assigned to another object , Will change this The direction of .
however , This rule is not easy to grasp . Look at the code below .
var obj ={
foo: function () {
console.log(this);
}
};
obj.foo() // obj
In the above code ,obj.foo Method execution , Its internal this Point to obj.
If this The method is not in the first layer of the object , At this time this It just points to the object at the current level , It doesn't inherit the layers above .
var a = {
p: 'Hello',
b: {
m: function() {
console.log(this.p);
}
}
};
a.b.m() // undefined
In the above code ,a.b.m Method in a The second layer of the object , Inside the method this Not pointing a, It's pointing to a.b, Because the following code is actually executed .
var b = {
m: function() {
console.log(this.p);
}
};
var a = {
p: 'Hello',
b: b
};
(a.b).m() // Equate to b.m()
If you want to achieve the desired results , Only write it as follows .
var a = {
b: {
m: function() {
console.log(this.p);
},
p: 'Hello'
}
};
If the method inside the nested object is assigned to a variable ,this Will still point to global objects .
var a = {
b: {
m: function() {
console.log(this.p);
},
p: 'Hello'
}
};
var hello = a.b.m;
hello() // undefined
In the above code ,m Is a method inside a multi-layer object . For simplicity , Assign it to hello Variable , When the result is called ,this Points to the top-level object . To avoid this problem , You can just m The object is assigned to hello, When called like this ,this The direction of will not change .
var hello = a.b;
hello.m() // Hello
Be careful
Avoid multiple layers this
In a closure this Pointing to window( You can remember that )
because this The direction of is uncertain , So don't include multiple layers of this.
var o = {
f1: function () {
console.log(this);
var f2 = function () {
console.log(this);
}();
}
}
o.f1()
// Object
// Window
The above code contains two layers this, Results after running , The first layer points to the object o, The second layer points to the global object , Because the following code is actually executed .
var temp = function () {
console.log(this);
};
var o = {
f1: function () {
console.log(this);
var f2 = temp();
}
}
One solution is to use a pointing outer layer in the second layer this The variable of .
var o = {
f1: function() {
console.log(this);
var that = this;
var f2 = function() {
console.log(that);
}();
}
}
o.f1()
// Object
// Object
The above code defines variables that, Fixed to the outer layer this, Then use in the inner layer that, It won't happen this Change of direction .
in fact , Use a variable to fix this Value , Then the inner function calls this variable , It's a very common practice , Please be sure to master .
JavaScript Provides strict patterns , This problem can also be avoided . In strict mode , If inside the function this Point to the top-level object , You're going to report a mistake .
var counter = {
count: 0
};
counter.inc = function () {
'use strict';
this.count++
};
var f = counter.inc;
f()
// TypeError: Cannot read property 'count' of undefined
In the above code ,inc Methods by ’use strict’ The declaration uses a strict pattern , At this time, the internal this Once you point to the top-level object , You're going to report a mistake .
边栏推荐
- HelloWorld
- Palindrome substring, palindrome subsequence
- Game 280 problem2: minimum operands to turn an array into an alternating array
- Introduction to opencv (I): image reading and display
- Deep learning -- feature point detection and target detection
- Transformer architecture understanding
- 跳槽字节跳动很难嘛?掌握这些技巧,你也能轻松通过
- Simple application of generating function
- Acreems energy efficiency management platform escorts the power safety of high-rise residential areas
- 【NVMe2.0b 14-4】Directive Send/Receive command
猜你喜欢

Halcon12+vs2013 C # configuration

【NVMe2.0b 14-2】Create/Delete Queue

HelloWorld

深度学习——Bounding Box预测

Palindrome substring, palindrome subsequence

An example of a single service in a cloud project driven by a domain

深度学习——循环神经网络

1. Problems related to OpenGL window and environment configuration

【JUC系列】Fork/Join框架之概览

Using typera+picgo to realize automatic uploading of markdown document pictures
随机推荐
全栈最全性能测试理论-总结
Deep learning -- feature point detection and target detection
HelloWorld
Deep learning - residual networks resnets
[JUC series] overview of fork/join framework
奇迹MU服务器租用选择 真实好用 稳定不卡 还能防入侵
Cesium learning notes (II) uploading data using rest API
深度学习——循环神经网络
How to handle the expired data of redis and what are the elimination mechanisms?
Cesium learning notes (VI) particle system
深度学习——卷积的滑动窗口实现
Environment configuration of ROS Aubo manipulator
Opencv4.2.0+vs2015 configuration
鲸探NFT数字臧品系统开发技术分享
AcrelEMS能效管理平台为高层小区用电安全保驾护航
MySQL cannot connect to the intranet database
More, faster, better and cheaper. Here comes the fastdeploy beta of the low threshold AI deployment tool!
小程序使用二维码插件
【花雕体验】13 搭建ESP32C3之PlatformIO IDE开发环境
【NVMe2.0b 14】NVMe Admin Command Set