新增函数方法
1. 函数的 length 属性
返回没有指定默认值的参数个数,rest 参数也不计入 length 属性。
(function(...args) {}).length // 0
(function (a = 0, b, c) {}).length // 0
(function (a, b = 1, c) {}).length // 1
一旦设置了参数的默认值,函数进行声明初始化时,参数会形成一个单独的作用域,等到初始化结束这个作用域就会消失。这种语法行为在不设置参数默认值时不会出现。
let x = 1;
function f(y = x) {
// 等同于 let y = x
let x = 2;
console.log(y);
}
f(); // 1
2. name 属性
返回函数的函数名。
- 将一个具名函数赋值给一个变量时,
name返回这个具名函数原本的名字。
const bar = function baz() {};
bar.name; // "baz"
Function构造函数返回的函数实例,name为"anonymous"。
(new Function).name; // "anonymous"
bind返回的函数,name会加上"bound "前缀。
function foo() {}
foo.bind({}).name; // "bound foo"
(function(){}).bind({}).name; // "bound "
3. rest 参数
ES6 引入了 rest 参数(...变量名),用于获取函数的多余参数。arguments 不是真正的数组(只能按下标访问),而 rest 参数是真正的数组。
class A {
constructor(...args) {
if (args.length === 3) {
this._x = args[0]; this._y = args[1]; this._z = args[2];
} else if (args.length === 2) {
this._x = args[0]; this._y = args[1]; this._z = 0;
} else {
throw new TypeError('args error!');
}
}
}
来源整理自:vue3js.cn 面试官系列



