面试题答案
一键面试- 分析
this
指向:- 在
outerFunction
中,this
指向全局对象(在浏览器环境下是window
,在 Node.js 环境下是global
),因为outerFunction
是作为一个普通函数调用的,非严格模式下普通函数调用时this
指向全局对象。 - 在
innerFunction
中,this
同样指向全局对象(在非严格模式下)。因为innerFunction
也是普通函数调用,在非严格模式下普通函数调用时this
指向全局对象。这里console.log(this.value)
实际访问的是全局对象的value
属性,而不是outerFunction
中的this.value
。
- 在
- 修改代码使内部函数中
this
指向外部函数的this
的方法:- 方法一:使用
var that = this
- 方法一:使用
function outerFunction() {
this.value = 10;
var that = this;
function innerFunction() {
console.log(that.value);
}
innerFunction();
}
outerFunction();
这里在 outerFunction
内部声明一个变量 that
并赋值为 this
,这样在 innerFunction
中通过 that
就能访问到 outerFunction
中的 this
所指向对象的属性。
- 方法二:使用
Function.prototype.bind
function outerFunction() {
this.value = 10;
function innerFunction() {
console.log(this.value);
}
var boundInnerFunction = innerFunction.bind(this);
boundInnerFunction();
}
outerFunction();
bind
方法创建一个新的函数,在调用新函数时,this
会被绑定到 bind
方法传入的第一个参数。这里将 innerFunction
的 this
绑定到 outerFunction
中的 this
,从而实现内部函数访问外部函数 this
的属性。
- 方法三:使用箭头函数
function outerFunction() {
this.value = 10;
const innerFunction = () => {
console.log(this.value);
};
innerFunction();
}
outerFunction();
箭头函数没有自己的 this
,它的 this
继承自外层作用域的 this
。这里外层作用域是 outerFunction
,所以箭头函数 innerFunction
中的 this
指向 outerFunction
中的 this
,能够正确访问 this.value
。