Retrieving values from Execution Contexts in JavaScript

前端 未结 6 915
长发绾君心
长发绾君心 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:25

    Local variables are intended to be non-accessible, also because they can depend on the function execution (how could you access that variable if the function has never been executed?).

    If you really need some trick, you can have a look at this:

    var person = function () {
        // Private
        var name = "Robert";
        return {
            getName : function () {
                return name;
            },
            setName : function (newName) {
                name = newName;
            }
        };
    }();
    alert(person.name); // Undefined
    alert(person.getName()); // "Robert"
    person.setName("Robert Nyman");
    alert(person.getName()); // "Robert Nyman"
    

    and notice that the function must be executed before you can use accessible methods.

提交回复
热议问题