gpt4 book ai didi

javascript - 从 JavaScript 中的执行上下文检索值

转载 作者:行者123 更新时间:2023-12-02 18:52:01 25 4
gpt4 key购买 nike

var value = 10;

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

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

console.log(value); // logs 30
console.log(window["outer_funct"]["value"]); // What I would like to log here is the value 20.
console.log(window["value"]); // logs 10
};

inner_funct();
};

outer_funct();

我相信第二个日志返回未定义的原因是因为 window["outer_funct"] 引用函数对象,并且函数对象没有与之关联的属性“值”。相反,我想做的是在调用 window["outer_funct"] 时引用执行上下文。这可以在inner_funct的执行上下文中完成吗?

最佳答案

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.

正确。

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?

不,您没有隐藏(在inner_funct中声明它)。如果该符号已被这样覆盖,您将无法访问它。当然,您可以将其放入另一个符号中:

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

如果您没有隐藏它,那么您可以在包含上下文中引用value,例如:

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

值得注意的是,原始代码的 window["value"] 返回 10 的唯一原因(顺便说一句,您也可以使用 window.value) 的原因是 var value = 10; 位于全局范围内。所有用 var 声明的变量都会成为全局对象的属性,在浏览器上通过 window 引用该全局对象(从技术上讲,window 本身就是全局对象上指向全局对象的属性)。

关于javascript - 从 JavaScript 中的执行上下文检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15720528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com