普通函数与箭头函数

const shape = {
  radius: 10,
  diameter() {
    return this.radius * 2;
  },
  perimeter: () => 2 * Math.PI * this.radius
};

shape.diameter();
shape.perimeter();
  • A: 20 and 62.83185307179586

  • B: 20 and NaN

  • C: 20 and 63

  • D: NaN and 63

答案: B

请注意,diameter是普通函数,而perimeter是箭头函数。

对于箭头函数,this关键字指向是它所在上下文(定义时的位置)的环境,与普通函数不同! 这意味着当我们调用perimeter时,它不是指向shape对象,而是指其定义时的环境(window)。没有值radius属性,返回undefined

练习

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5   <meta charset="UTF-8">
 6   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7   <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8   <title></title>
 9 </head>
10 
11 <body>
12 <div id="div">2233</div>
13 <ul>
14   <li>
15     知识点一:
16     Math.PI 表示一个圆的周长与直径的比例,约为3.14159
17     Math.PI = π≈3.14159
18   </li>
19   <li>
20     知识点二:
21     js里面的换行 

22   </li>
23   <li>
24     知识点三:
25     
换行在document.write中不起作用
26   </li>
27   <li>
28     知识点四:
29       js里innerText用法是 = 赋值,而不是innerText()
30   </li>
31   <li>
32     知识点五:
33       document.getElementById与document.write输出顺序的不同
34   </li>
35 </ul>
36 </body>
37 
38 </html>
39 <script type="text/javascript">
40   const shape = {
41     radius: 10,
42     a(){
43       return this.radius * 2
44     },
45     b: () => 2 * Math.PI * this.radius
46   }
47   let result = `方法a的结果是:${shape.a()}; 
 方法b的结果是:${shape.b()}`
48   document.write(`document.write输出结果:${result}`)
49   document.getElementById('div').innerText = `document.getElementById输出结果:
 ${result}`
50 </script>
index.html
原文地址:https://www.cnblogs.com/wang715100018066/p/11081872.html