Retrieving values from Execution Contexts in JavaScript

前端 未结 6 916
长发绾君心
长发绾君心 2021-01-27 15:40
var value = 10;

var outer_funct = function(){
    var value = 20;

    var inner_funct = function(){
        var value = 30;

        console.log(value); // logs 30
            


        
6条回答
  •  深忆病人
    2021-01-27 16:06

    I believe the reason the second log is returning undefined is because window["outer_funct"] refers to the function object, and the function object doesn't have a property "value" associated with it.

    Correct.

    Instead, what I would like to do is refer to the execution context when window["outer_funct"] is invoked. Is this possible to do within the execution context of inner_funct?

    No, not with you having shadowed value (declared it in inner_funct). You have no way of getting to it with that symbol having been overridden like that. You could, of course, grab it into another symbol:

    var value = 10;
    
    var outer_funct = function(){
        var value = 20;
    
        var outer_value = value;
    
        var inner_funct = function(){
            var value = 30;
    
            console.log(value);        // logs 30
            console.log(outer_value);  // logs 20
            console.log(window.value); // logs 10
        };
    
        inner_funct();
    };
    
    outer_funct();
    

    If you hadn't shadowed it, then you could refer to value in the containing context, e.g.:

    var value1 = 10;
    
    var outer_funct = function(){
        var value2 = 20;
    
        var inner_funct = function(){
            var value3 = 30;
    
            console.log(value3); // logs 30
            console.log(value2); // logs 20
            console.log(value1); // logs 10
        };
    
        inner_funct();
    };
    
    outer_funct();
    

    It's worth noting that the only reason that your original code's window["value"] returned 10 (btw, you could also use window.value) is that the var value = 10; is at global scope. All variables declared with var become properties of the global object, which on browsers is referred to via window (technically, window is, itself, just a property on the global object that points back to the global object).

提交回复
热议问题