function func() {
function a () {
console.log(b)
}
a();
const b = 'bbb'
}
func()
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
上面代码会输出什么?
答案:
ReferenceError: Cannot access 'b' before initialization
# 下面的代码会输出什么?
function A(name) {
this.name = name || 'Tom'
this.msg = "use 'this.' set in function"
}
function B() {};
B.prototype = A;
var b = new B();
console.log(b.name);
console.log(b.msg);
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
答案是:
A
undefined
1
2
2
# 分析
b.name
返回 A
,是因为b
上面没有name
属性,他就会沿着原型链向上查找,然而 b.__proto__
为函数A
,每一个函数都有一个属性为name,其值是函数的名字。
function abc() { /* 这是一个名为'abc'的函数 */ }
abc.name // -> 'abc'
1
2
2
b.msg
为什么是undefined
哪? 因为b.__proto__
是 函数A
,那怎么修改才能拿到msg
哪?
B.prototype = new A();
1
修改后的输出:
Tom
VM731:12 use 'this.' set in function
1
2
2