首页 > 解决方案 > 'this' 和普通变量声明之间的区别

问题描述

this在我的函数中声明变量与通常使用letor声明有什么区别var

const controller = (function() {
  this.name = 'John';
})();

const controller2 = (function() {
  let name = 'Mary';
})();

标签: javascriptfunctionthis

解决方案


this你的函数里面是window对象。因此,您不是在创建变量,而是在向窗口对象添加属性

console.log((function(){return this})() === window)


推荐阅读