赞
踩
- const/let 函数名 = 参数 => 函数体。
- // 3.如何将一般函数改写成箭头函数
- // 一般函数形式
- function add() {}
- // 箭头函数形式
- const add = () => {};
- 只有在函数调用的时候 this 指向才确定,不调用的时候,不知道指向谁。
- this 指向和函数在哪儿调用没关系,只和谁在调用有关。
- 没有具体调用对象的话,this 指向 undefined,在非严格模式下,转向 window,默认是非严格模式。
- 箭头函数没有自己的 this。
- 一般函数:
- 箭头函数:
- 点击按钮开始计时。
- 使用一般函数需要使用that=this,对当前的this对象进行保存。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>模板字符串的应用</title> <style> body { padding: 50px 0 0 250px; font-size: 30px; } #btn { width: 100px; height: 100px; margin-right: 20px; font-size: 30px; cursor: pointer; } </style> </head> <body> <button id="btn">开始</button> <span id="result">0</span> <script> const btn = document.getElementById('btn'); const result = document.getElementById('result'); const timer = { time: 0, start: function () { let that = this; btn.addEventListener( 'click', function () { setInterval(function () { that.time++; result.innerHTML = that.time; }, 1000); }, false ); } }; timer.start(); </script> </body> </html>
- 使用箭头函数,由于箭头函数没有this会自动向外层逐级查找,这样可以剩去that=this操作。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>模板字符串的应用</title> <style> body { padding: 50px 0 0 250px; font-size: 30px; } #btn { width: 100px; height: 100px; margin-right: 20px; font-size: 30px; cursor: pointer; } </style> </head> <body> <button id="btn">开始</button> <span id="result">0</span> <script> const btn = document.getElementById('btn'); const result = document.getElementById('result'); const timer = { time: 0, start: function () { btn.addEventListener( 'click', () => { setInterval(() => { this.time++; result.innerHTML = this.time; }, 1000); }, false ); } }; timer.start(); </script> </body> </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。