面试题答案
一键面试- 分析
Outer
函数调用过程及this
绑定:- 当执行
const result1 = new Outer();
时:- 首先,
new
操作符创建一个新的空对象,这个新对象会被作为this
绑定到Outer
函数内部。 - 在
Outer
函数内部,执行this.value = 1;
,此时this
指向新创建的对象,所以新对象拥有了属性value
且值为1
。 - 然后定义了内部函数
Inner
。当执行return Inner();
时,由于Inner
函数是在非严格模式下直接调用(没有通过某个对象调用,如obj.Inner()
这种形式),在非严格模式下,this
会默认绑定到全局对象(在浏览器环境中是window
,在 Node.js 环境中是global
)。因为全局对象没有value
属性,所以返回undefined
。即result1
的值为undefined
。
- 首先,
- 当执行
- 分析
AnotherOuter
函数调用过程及this
绑定:- 当执行
const result2 = new AnotherOuter();
时:new
操作符创建一个新的空对象,这个新对象作为this
绑定到AnotherOuter
函数内部。- 在
AnotherOuter
函数内部,执行this.value = 2;
,此时this
指向新创建的对象,新对象拥有了属性value
且值为2
。 - 接着定义
innerFunc
,通过bind(this)
方法,bind
方法会创建一个新函数,并且将this
绑定到传入的参数this
(这里就是AnotherOuter
函数内部的this
,即新创建的对象)。所以当执行return innerFunc();
时,this.value
访问的是新创建对象的value
属性,值为2
。即result2
的值为2
。
- 当执行
- 最终输出结果:
- 执行
console.log(result1, result2);
输出undefined 2
。
- 执行
所以代码的输出结果是 undefined 2
。