一、函数对象
函数的类型是对象。
1.属性“name”
函数都有个“name”,即使函数被创建时没有名字,名称赋值的逻辑也能给它赋予一个正确的名字,然后进行赋值。
const fn = function () { };
function fnn() {
}
const user = {
sayBye: function () { }
};
const arr = [function () { }];
console.dir(fn.name); //fn
console.dir(fnn.name); //fnn
console.dir(user.sayBye.name); //sayBye
console.dir(arr[0].name); //空
2.属性“length”
length 返回形式参数个数,不包括剩余参数“...e”
function fn(a, b, c) { // 形式参数
console.log(fn.name, fn.length) // 统计形式参数个数,不包括剩余参数“...e”
}
fn(1, 2, 3, 4); // 实际参数,fn 3
const user = {
sayBye: function (x, y, z) {
console.log(this.sayBye.name, this.sayBye.length)
}
};
user.sayBye(); //sayBye 3
使用arguments,以参数在参数列表中的索引作为键,存储所有实际参数,以类数组对象的形式输出所有函数参数 。
3.自定义属性
在函数中随便添加属性,方法
function fn(a, b, c) { };
fn.title = "hello";
fn.say = function () {
console.log(this.title)
};
console.dir(fn);// ƒ fn(a, b, c) say: ƒ () title: "hello"
fn.say(); // hello
现在 title 被直接存储在函数里,而不是它外部的词法环境。
函数中的属性方法在函数调用后才会产生
4.命名函数(NFE)
一个普通的函数表达式给它加一个名字:
let
sayHi
=
function
func
(
who
)
{
alert
(
`
Hello,
${
who}
`
)
;
}
;
- 它允许函数在内部引用自己,确保只会引用当前函数。
- 它在函数外是不可见的。
二、定时器
1.setTimeout
将函数推迟到一段时间间隔之后再执行 ,存在返回值id,表示自己是第几个定时器
let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
const h1 = setTimeout(
function (a, b) {
console.log("already 5s,present", a, b)
}, // 执行的函数
5000, // 执行函数前等待的时间
"css", // 作为参数,传入前面的函数
"html" // 作为参数,传入前面的函数
);
2.setInterval
setInterval 每间隔给定的时间周期性执行
let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)
const h1 = setInterval(
function (a, b) {
console.log("already 3s,present", a, b)
}, // 执行的函数
3000, // 执行函数前等待的时间,执行后循环
"css", // 作为参数,传入前面的函数
"html" // 作为参数,传入前面的函数
);
3.嵌套的setTimeout
周期性调度 嵌套的setTimeout
嵌套的 setTimeout 相较于 setInterval 能够更精确地设置两次执行之间的延时。
let timerId = setTimeout(function tick() {
console.log('tick');
timerId = setTimeout(tick, 2000); // (*)
}, 2000);
// 精度要求低的时候用 setInterval
// 精度高一点的时候用 setTimeout
4.同步代码,异步代码
console.log("1"); // 同步代码
console.log("2"); // 同步代码
setTimeout(
() => {
console.log("hello1") // 异步代码
console.log("hello2") // 异步代码
},
0, // 可以不传参数,默认0
);
console.log("hi..."); // 同步代码
// 同步代码先执行,异步代码后执行
setTimeout中的执行代码为异步代码,一般的代码为同步代码;
同步代码先执行,所有同步代码执行完后异步代码执行