除了最常用的 console.log(),Web API 接口的 console 对象还提供了一些好用的方法。
console.assert(assertion, obj)
设置断言 assertion,当其值为 false 的时候向控制台输出 obj。
let str = "assertion is falsy"
console.assert({}==={}, str); // VM378:2 Assertion failed: assertion is falsy
console.dir(obj)
在控制台中显示指定 JavaScript 对象的属性,可以用于查看函数对象的作用域链属性[[scope]]。
let a = 1;
function foo() {
console.dir(foo);
function bar() {
console.dir(bar);
function baz(){
console.dir(baz);
};
baz();
}
bar();
}
foo();
console.dir() 依次打印:
foo()
arguments: null
caller: null
length: 0
name: "foo"
...
[[Scopes]]: Scopes[2]
0: Script {a: 1}
1: Global {window: Window, self: Window, document: document, name: "", location: Location, …}
bar()
arguments: null
caller: null
length: 0
name: "bar"
...
[Scopes]]: Scopes[3]
0: Closure (foo) {bar: ƒ}
1: Script {a: 1}
2: Global {window: Window, self: Window, document: document, name: "", location: Location, …}
baz()
arguments: null
caller: null
length: 0
name: "baz"
prototype: {constructor: ƒ}
...
[[Scopes]]: Scopes[4]
0: Closure (bar) {baz: ƒ}
1: Closure (foo) {bar: ƒ}
2: Script {a: 1}
3: Global {window: Window, self: Window, document: document, name: "", location: Location, …}
可以清楚地检查当前函数的作用域链以及其中闭包变量的依赖(如有)。
console.trace()
可以在函数内调用,用于显示当前函数所在的堆栈。
function foo() {
function bar() {
/*
console.trace
bar @ VM87:3
foo @ VM87:6
(anonymous) @ VM87:9
*/
console.trace();
function baz(){};
baz();
}
bar();
}
foo();