var name = 'the window';
var object = {
name: 'my object',
getNameFunc: function () {
console.log(this === window) // false
return function () {
/** 此处的作用域链应该是什么样子
* 为什么这个地方的this变成了window而不是object
*/
console.log(this === window) // true
return this.name;
}
},
test: function () {
var name = this.getNameFunc()()
return name;
}
};
console.log(object.test()) // the window
js作用域链和闭包中的this的问题?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
天际的海浪 2018-10-11 09:06关注this是调用函数的对象,和作用域链或闭包都没有关系
var name = this.getNameFunc()()
等同
var x = this.getNameFunc();
var name = x()this.getNameFunc()这样调用时,getNameFunc是以this对象的方法调用的,会把 . 前面的this对象传递给getNameFunc内的this
而 x() 是直接调用的。对于直接调用的函数,在非严格模式下函数内的this默认值就是window,严格模式下是undefined解决 无用评论 打赏 举报