02-模板字符串和箭头函数
# 模板字符串
使用模板字符串,方便注入表达式内容。
let name = 'Alice';
const info = `我的名字是${name}`;
2
注意:模板字符串中,所有的空格、换行或缩进都会被保留在输出之中。
const message = `第一行
第二行
第三行`;
console.log(message);
2
3
4
输出内容如下:
第一行
第二行
第三行
2
3
# 箭头函数
# 箭头函数写法
const add = (x, y) => {
return x + y;
};
console.log(add(1, 1));
2
3
4
箭头函数简化:
单个参数可以省略圆括号
const add = x => { return x + 1; }; console.log(add(1));
1
2
3
4
5单行函数体可以同时省略
{}
和return
const add = (x, y) => { return x + y; }; const add = (x, y) => x + y; console.log(add(1, 1));
1
2
3
4
5
6
7如果箭头函数返回单行对象,可以在
{}
外面加上()
,让浏览器不再认为那是函数体的花括号const add = (x, y) => { return { value: x + y }; }; const add = (x, y) => ({ value: x + y });
1
2
3
4
5
6
7
8
9
# 不适用箭头函数的情况
以下场景不适用箭头函数
- 作为构造函数
- 需要 this 指向调用对象的时候
- 需要使用 arguments 的时候
(1)箭头函数不能作为构造函数
// 不能作为构造函数,因为箭头函数没有 this
const Person = () => {};
// 使用new关键字调用构造函数,会报错
new Person(); // Uncaught TypeError: Person is not constructor
2
3
4
5
(2)需要 this 指向调用对象的时候,只能使用一般函数
document.onclick = function () {
console.log(this);
};
document.addEventListener(
'click',
function () {
console.log(this);
},
false
);
2
3
4
5
6
7
8
9
10
11
(3)需要使用 arguments 的时候。箭头函数中没有 arguments。
// 一般函数中可以使用箭头函数
function add() {
console.log(arguments);
}
add(1, 2, 3, 4, 5);
// 箭头函数中没有 arguments
const add2 = () => {
console.log(arguments); // 报错
}
2
3
4
5
6
7
8
9
10
后续会介绍箭头函数中使用==剩余参数==来代替一般函数中的 arguments。
# this 指向
# 非箭头函数中的 this 指向
全局作用域中的 this 指向 window。
console.log(this); // window
一般函数(非箭头函数)中的 this 指向由谁调用决定。
非严格模式下,函数没有通过任何人调用,则其中 this 先指向 undefined,然后再转而指向 window。
// 非严格模式
function add() {
console.log(this);
}
add(); // window
2
3
4
5
6
严格模式下,这种情况 this 直接指向 undefined。
// 非严格模式
'use strict';
function add() {
console.log(this);
}
add(); // undefined
2
3
4
5
6
7
8
如果显示通过 window 调用函数,则无论严格非严格,this 都指向 window。
window.add(); // window
总结:
全局作用域中的 this 指向 window
一般函数只有在函数调用的时候 this 指向才确定,不调用的时候,不知道指向谁
this 指向和函数在哪儿调用没关系,只和谁在调用有关
没有具体调用对象的话,非严格模式下指向 window,严格模式下 this 指向 undefined
构造函数中 this 指向构造出的对象
# 箭头函数中的 this 指向
箭头函数没有自己的 this。
下例中,现在函数作用域中查找 this,由于箭头函数没有自己的 this,找不到 this,则通过作用域链的机制向外层找。外层对象 calc 没有作用域,再外层就是全局作用域了了,所以最后 this 指向全局作用域中的 this,也就是 window。
const calc = {
add: () => {
console.log(this);
}
};
calc.add(); // window
2
3
4
5
6
所以总结箭头函数中的 this,就是要向外找。