在本地作用域内使用相同名称的控制台全局作用域变量

时间:2019-02-11 05:19:00

标签: javascript node.js variables scope

我想打印使用let声明的全局范围变量,该变量在函数内部也以相同的名称声明。

我使用过window对象,但一直在说未定义window。

var globalLet = "This is a global variable";
 
function fun() {
  var globalLet = "This is a local variable";
  console.log(globalLet); //want to print 'This is global variable' here.
}
fun();

3 个答案:

答案 0 :(得分:1)

使用this.varname访问全局变量

var globalLet = "This is a global variable";

function fun() {
  var globalLet = "This is a local variable";
  console.log(this.globalLet); //want to print 'This is global variable' here.
}
fun();

答案 1 :(得分:1)

this的值设置为null时,它将始终映射到全局对象(在非严格模式下)。

这里只是声明一个匿名函数并将this设置为null,然后通过传递全局对象globalLet的属性立即调用它,将始终返回全局值。

警告:这在严格模式下不起作用,严格模式下this指向null

var globalLet = "This is a global variable";
 
function fun() {
  var globalLet = "This is a local variable";
  globalLet = (function(name){return this[name]}).call(null, "globalLet");
  console.log(globalLet); //want to print 'This is global variable' here.
}
fun();

根据ES5 spec

  

15.3.4.4 Function.prototype.call(thisArg [,arg1 [,arg2,…]])#Ⓣ在具有参数的对象func上调用call方法时   thisArg和可选参数arg1,arg2等,以下步骤是   拍摄:

     

如果IsCallable(func)为false,则抛出TypeError异常。

     

让argList为空列表。

     

如果使用多个参数调用了此方法,则向左移   以arg1开头的正确顺序将每个参数附加为最后一个   argList的元素

     

返回调用func的[[Call]]内部方法的结果,   提供thisArg作为this值,并提供argList作为   争论。

     

调用方法的length属性为1。

     

注意:thisArg值未经修改即作为this传递   值。这是对版本3(未定义或为null)的更改   将thisArg替换为全局对象,并将ToObject应用于   所有其他值,该结果将作为此值传递。

答案 2 :(得分:1)

在全局上下文中使用this关键字,它已绑定到全局对象。

var globalLet = "This is a global variable";
 
function fun() {
  var globalLet = "This is a local variable";
  console.log(this.globalLet); //want to print 'This is global variable' here.
}
fun();

相关问题