
小白学习Vue(9)--箭头函数 | this指向 | 指令缩写
箭头函数中的
发布日期:2021-05-08 02:04:52
浏览次数:22
分类:精选文章
本文共 1994 字,大约阅读时间需要 6 分钟。
9.1 箭头函数
无参多行形式
通过 function
关键字定义函数的同时,我们也可以利用箭头 =>
进行简洁的函数定义。无参的箭头函数可以通过多行代码实现功能。
const a = () => { console.log("无参多行的箭头函数一"); console.log("无参多行的箭头函数二");};a();
无参单行简写形式
对于不需要多行操作的无参函数,箭头函数可以进一步简化为单行代码形式。
const b = () => console.log("无参单行简写的箭头函数一");b();
有参多行形式
对于需要接受多个参数的函数,箭头函数同样支持多行代码实现。
const cc = function (numA, numB) { console.log('numA:%s,numB:%s', numA, numB); return numA + numB;};console.log("-----:" + cc(2, 4));const c = (numA, numB) => { console.log('numA:%s,numB:%s', numA, numB); return numA + numB;};console.log("-----:" + c(2, 4));
有参单行简写形式
当函数的实现可以在一行内完成时,可以进一步简化为单行箭头函数。
const d = (numA, numB) => numA + numB;console.log("-----:" + d(6, 8));const e = numC => d(numC, numC);console.log("-----:" + e(4));const num = 2;setTimeout(() => { console.log("-----nummm:" + num);}, 1000);
关于函数参数的使用
在一个函数中需要将另一个函数作为参数时,利用箭头函数可以更加简洁地实现这一功能。
9.2 this指向
在 JavaScript 中,this
的指向具有特定的规则,具体取决于函数的执行上下文。以下是 this
指向的一些常见场景:
在实例方法中使用
如果函数是通过实例方法定义的,那么 this
会指向该实例。
var AAA = new Vue({ methods: { aaa: function () { console.log("aaaaaa_:" + this); // object } }});AAA.aaa(); // this 指向实例对象
箭头函数中的 this
对于箭头函数来说,this
的指向没有像传统函数那样自动指向对象,而是会向外层寻找。在全局环境中,this
会指向 window
。
const BBB = () => console.log("bbbbbb_:" + this); // this 指向 windowBBB();
定义函数的函数
在函数定义时,如果没有使用 new
关键字,this
会默认指向 window
。
function test() { console.log("window_:" + this); // window}test();
在对象方法中使用箭头函数
如果使用箭头函数作为对象方法,那么 this
会指向该对象。
var obj = { functionA() { setTimeout(function () { console.log("----" + this); // window }, 1000); console.log("****" + this); // object setTimeout(() => { console.log("====" + this); // object }, 1000); }};obj.functionA();
9.3 常用指令指向
在 JavaScript 中,某些内置对象和函数的 this
指向也具有特殊规则。例如,setTimeout
中的回调函数会将 this
指向 window
,而不是定义该函数的对象。
setTimeout(() => { console.log("window_");}, 1000);
通过理解这些规则,我们可以更准确地控制 this
的指向,避免在不同情境下出现意想不到的问题。