【问题标题】:Console global scope variable of same name inside local scope [duplicate]本地范围内同名的控制台全局范围变量[重复]
【发布时间】:2019-07-04 13:56:43
【问题描述】:

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

我使用了窗口对象,但它一直说窗口没有定义。

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();

【问题讨论】:

  • 你能给出你得到的完整错误
  • 你说的“我用过window object”是什么意思?该代码是什么样的?您是在浏览器中运行它还是通过 Node.js 之类的东西运行它?
  • repl.it/@MukulLatiyan/javascript 访问此链接并尝试运行它。
  • @Phil 通过节点。
  • Window对象是浏览器提供的,node没有

标签: javascript node.js variables scope


【解决方案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();

【讨论】:

    【解决方案2】:

    当您将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, ... ] ] ) # Ⓣ Ⓡ 当 call 方法在一个带参数的对象 func 上被调用时 thisArg 和可选参数 arg1、arg2 等,以下步骤是 采取:

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

    令 argList 为空列表。

    如果这个方法被调用时使用了多个参数,那么在 left to 以 arg1 开头的正确顺序将每个参数附加为最后一个 argList 的元素

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

    调用方法的length属性为1。

    注意 thisArg 值是在没有修改的情况下传递的 this 价值。这是对第 3 版的更改,其中未定义或 null thisArg 被替换为全局对象,并且 ToObject 应用于 所有其他值,并且该结果作为 this 值传递。

    【讨论】:

      【解决方案3】:

      在全局上下文中使用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();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-30
        • 1970-01-01
        • 2013-11-06
        • 1970-01-01
        • 2016-11-13
        • 1970-01-01
        • 2019-06-01
        • 2021-03-05
        相关资源
        最近更新 更多