JS arrow function this points to related practice

TaRiz 2021-04-07 21:48:26
js arrow function points related


Arrow function this Pointing is determined at the time of definition .

For this conclusion , In fact, we have to discuss it in different situations .

  1. When in class When defining methods using arrow functions , It was decided at the time of its definition .
class Temp {
constructor() {
this.name = 'tariz';
}
getNameArrow = () => {
console.log(this.name);
}
getName() {
console.log(this.name);
};
};
 Copy code 

The above code is passed babel After conversion

function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class Temp {
constructor() {
_defineProperty(this, "getNameArrow", () => {
console.log(this.name);
});
this.name = "tariz";
}
getName() {
console.log(this.name);
}
}
 Copy code 

We'll find that when we use arrow functions to define methods of a class , In fact, the current method is bound to this Attribute , When we don't take the initiative call、bind、apply change this When pointing , Call... Anyway getNameArrow Method ,this All point to instances of this class .

  1. If not in the above 1 Under the circumstances , Use the arrow function , Arrowhead function this The point depends on the execution context above the definition time this( Maybe the expression is not clear enough ), Let's look directly at the following code for analysis .
const obj = {
name: 'tariz',
getName: () => {
console.log(this.name);
}
};
console.log(obj.getName()); // undefined
 Copy code 

babel After conversion

var _this = this;
var obj = {
name: "tariz",
getName: function getName() {
console.log(_this.name);
}
};
 Copy code 

The output value of the above code is undefined, This result is not surprising , Next I'll go through chrome Browser debugging explanation .

Combined with the conclusion of the second point , Pointing to the upper execution context this, At present getName The upper execution context calls the anonymous function at the beginning ( here this by window), therefore getName Of this Pointing to window,window It doesn't have this property on it , So for undefined.

Why when debugging the browser , The first function on the function call stack is an anonymous function , It can be understood in this way , be familiar with webpack If you pack it , There is a realization inside commonjs standard , Each module is an anonymous function , Parameter is module、module.exports、module.require, Here we can compare our code to run in an anonymous function , Parameter is window.

Next, let's take another example to further analyze .

const obj = {
name: 'tariz',
getName() {
const showMyName = () => {
console.log(this.name);
};
showMyName();
}
};
const showMyNameWrapper = obj.getName;
obj.getName(); // tariz
showMyNameWrapper(); // undefined
 Copy code 

In the above example ,showMyName Function this The direction of the direction depends on getName The execution context of the function this, however getName The function execution context is unstable , In its execution of dynamic decisions .

stay obj.getName() in ,getName Function execution context this by obj, therefore showMyName The print result is tariz.

stay showMyNameWrapper in ,getName The function performs the this by window, Should be current getName Call... In the global context , So the value is undefined;

Arrowhead function this Point to... Depending on the execution context of the upper layer this

function Parent(s) {
s();
};
const obj = {
name: 'egg',
getName: function () {
new Parent(() => { console.log('parent', this.name) });
setTimeout(() => { console.log('time:', this.name) });
console.log(this.name);
const add = () => { console.log(this.name) };
add();
}
};
obj.getName();
// parent egg
// egg
// egg
// time: egg
 Copy code 

babel Compile arrow functions :

function Parent(s) {
s();
}
var obj = {
name: "egg",
getName: function getName() {
var _this = this;
new Parent(function () {
console.log("parent", _this.name);
});
setTimeout(function () {
console.log("time:", _this.name);
});
console.log(this.name);
var add = function add() {
console.log(_this.name);
};
add();
}
};
obj.getName();
// At this time this Has been identified as getName Execution context this
 Copy code 

The above code is more complex than the previous example , adopt chrome Debug to analyze .

When it comes to creating Parent At instance time , When executing the arrow function , We find that the current function call stack is 4 individual , The anonymous function pointed by the red arrow is the current arrow function , Although the upper execution context is Parent, But arrow function execution is defined in its definition this Pointing is the above conjecture , all this It still points to getName Execution context this, That is to say obj.

Empathy setTimeout There's a similar shift . therefore this Also execute getName Execution context this, This process is not repeated , Interested in debugging .

版权声明
本文为[TaRiz]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/04/20210407213623170t.html

  1. Element tree control: invalid to modify current node key
  2. linux下安装apache(httpd-2.4.3版本)各种坑
  3. How to install Apache (httpd-2.4.3) under Linux
  4. 程序员业余时间写的代码也算公司的?Nginx之父被捕引发争议
  5. Nacos serialize for class [com.alibaba.nacos.common.http.HttpRestResult] failed.
  6. Do programmers write code in their spare time? Controversy over the arrest of nginx's father
  7. Nacos serialize for class [ com.alibaba.nacos . common.http.HttpRestResult ] failed.
  8. Seamless management of API documents using eolink and gitlab
  9. vue 的基础应用(上)
  10. 28岁开始零基础学前端,这些血的教训你一定要避免
  11. Basic application of Vue
  12. Starting at the age of 28, you must avoid these bloody lessons
  13. Ubuntu 16.04 can not connect to the wireless solution and QQ installation
  14. Industry security experts talk about the rapid development of digital economy, how to guarantee the security of data elements?
  15. 利用Vue实现一个简单的购物车功能
  16. Behind the "tireless classroom" and teacher training, can byte education really "work wonders"?
  17. Using Vue to realize a simple shopping cart function
  18. 【css】伪类和伪类元素的区别
  19. 【css效果】实现简单的下拉菜单
  20. 【vue】父子组件传值
  21. The difference between pseudo class and pseudo class elements
  22. [CSS effect] simple drop-down menu
  23. [Vue] value transfer by parent-child component
  24. 【css】设置table表格边框样式
  25. 【css】修改input,textarea中的placeholder样式
  26. vue-router的两种模式(hash和history)及区别
  27. CSS3的滤镜filter属性
  28. [CSS] set table border style
  29. [CSS] modify the placeholder style in input and textarea
  30. Two modes of Vue router (hash and History) and their differences
  31. Filter property of CSS3
  32. 全局安装gulp 报错问题解决
  33. Solution of error report in global installation of gulp
  34. 18个好用的自定义react hook
  35. 你应该知道的常用服务器HTTP状态码?
  36. 18 user defined react hooks
  37. What HTTP status codes should you know about common servers?
  38. 手把手教你打造属于自己团队的前端小报系统
  39. Hand in hand to teach you to build your own front-end tabloid system
  40. In 2021, enterprise SEO actual operation, how to less update, batch ranking regional words?
  41. vue cli4.0 快速搭建项目详解
  42. Vue cli4.0 quick build project
  43. vue-cli脚手架安装
  44. Installation of Vue cli scaffold
  45. [JS knowledge] method of getting elements from DOM
  46. 【jQuery效果】文字滚动
  47. [jQuery effect] text scrolling
  48. [front end] live broadcast of user experience optimization series, real-life sharing of front-line celebrities
  49. React native introduces third party Android SDK
  50. Using html2canvas to generate shared images, CDN images do not show the problem
  51. Using hooks to write react components
  52. Explain the module hot replacement function of webpack in detail
  53. An incomplete guide to writing a simple native wechat applet
  54. How JavaScript calculates 1 + 1 - Part 1 creates a source string
  55. Jsonp method to solve cross domain problems
  56. Canvas animation demo (from zero to one)
  57. El dialog of elementui component encapsulation
  58. Transition group of Vue source code
  59. When encountering bracket validity, next larger element, specific minimum value, try stack
  60. Vue3 virtual DOM