# 我不知道还可以用 JS 做的 6 件事
# Function 构造函数
不管是通过函数定义语句还是函数直接量表达式,函数的定义都要使用 function()关键字。单函数还可以通过 Function()构造函数来定义
const diff = new Function("a", "b", "return a - b");
diff(20, 13); // 7
// 等价于
const diff = function(a, b) {
return a - b;
};
diff(20, 13);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# with 语句
JavaScript 有个 with 关键字, with 语句的原本用意是为逐级的对象访问提供命名空间式的速写方式。也就是在指定的代码区域, 直接通过节点名称调用对象
with(object)
1
该语句可以有效地将 object 添加到作用域链的头部,然后执行 statement,再把作用域链恢复到原始状态。
const book = {
author: "前端小智",
title: "我不知道还可以用 JS 做的 6 件事",
};
with (book) {
console.log(author); // 前端小智
console.log(title); // 我不知道还可以用 JS 做的 6 件事
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
但是:尽量避免使用
# + 操作符
# 给函数赋值属性
function sayHello() {
if ((sayHello.country = "US")) {
return alert("Hi there!");
}
if ((sayHello.country = "FR")) {
return alert("Bonjour !");
}
if ((sayHello.country = "GR")) {
return alert("Guten Tag !");
}
return alert("Hi");
}
sayHello.country = "FR";
sayHello(); // alert('Bonjour !');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# arguments.callee.caller
我们可以使用 arguments.callee.caller 来查看哪个函数调用了当前函数。arguments JS 普通函数的默认值。arguments.callee.caller 告诉我们谁调用了该函数。类似于只有一层 console.trace()。
function sayHello() {
console.log(arguments.callee.caller) // [Function: start]
}
(function start() {
sayHello()
})()
1
2
3
4
5
6
7
2
3
4
5
6
7
另外arguments.callee表示引用当前正在运行的函数。
function sayHello() {
console.log(arguments.callee) // [Function: sayHello]
}
(function start() {
sayHello()
})()
1
2
3
4
5
6
7
2
3
4
5
6
7