- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我将全局变量x声明为:
var x = "I am window.x";
最佳答案
看来您已经理解得很好(我在下面用您的术语选择了一个小巧的选择)。构造函数内的局部变量就是:构造函数内的局部变量。它们根本不属于由构造函数初始化的实例的一部分。
这都是“范围”在JavaScript中的工作方式的结果。调用函数时,将为该函数调用创建执行上下文(EC)。 EC有一个叫做变量上下文的东西,它有一个绑定(bind)对象(我们称它为“变量对象”,是吗?)。变量对象保存所有var
和函数参数以及函数内定义的其他内容。这个变量对象是很真实的东西,对于闭包的工作方式非常重要,但是您不能直接访问它。构造函数中的x
是为调用构造函数而创建的变量对象的属性。
所有作用域都有一个变量对象。魔术是全局作用域的变量对象是全局对象,在浏览器中是window
。 (更准确地说,window
是变量对象上的一个属性,它引用回该变量对象,因此您可以直接引用它。函数调用中的变量对象没有任何等效属性。)因此,您在全局范围内定义的x
是window
的属性。
我 promise 的那种挑剔的术语:您已经说过:
If call a global function, the window object will be passed in as the context (the “this” keyword).
myGlobalFunction();
this
将是调用期间的全局对象(
window
)。但是,您有很多其他方法可以调用该全局函数,而不会使用它。例如,如果您将该“全局”函数分配给对象的属性,然后通过该属性调用该函数,则调用内的
this
将是该属性所属的对象:
var obj = {};
obj.foo = myGlobalFunction;
obj.foo(); // `this` is `obj` within the call, not `window`
obj['foo'](); // Exactly the same as above, just different notation
call
或
apply
功能来显式设置
this
:
var obj = {};
myGlobalFunction.call(obj, 1, 2, 3); // Again, `this` will be `obj`
myGlobalFunction.apply(obj, [1, 2, 3]); // Same (`call` and `apply` just vary
// in terms of how you pass arguments
this
的更多信息)this
(甚至更多有关函数和this
的信息)I just want to check my understanding: In any scope (global or function) there are always 2 objects: a “this” object (what is that called?) and a “variable object”. In the global scope, these 2 objects are the same. In a function’s scope, they are different, and the “variable object” is not accessible. Is that correct?
this
与
无关,但与无关。如果您要使用其他语言的JavaScript,这将令人惊讶,但这是事实。 JavaScript中的
this
(尽管有时可能会引起误解,有时也称为“上下文”)完全由调用函数的方式定义,而不是由定义函数的位置定义。您可以通过几种方式之一调用函数时设置
this
(请参见上面的答案和链接)。从
this
的 Angular 来看,定义全局范围的函数与定义在另一个函数内的函数之间没有任何区别。零。齐尔奇
this
(可以是任何东西)和变量对象。实际上,通常有多个可变对象按链排列。这称为范围链。当您尝试检索自由变量的值(不合格的符号,例如
x
而不是
obj.x
)时,解释器会在最上方的变量对象中查找具有该名称的属性。如果找不到,则转到链中的下一个链接(下一个外部作用域),然后查看该变量对象。如果没有,则查看链中的下一个链接,依此类推,依此类推。而且您知道链中的最终链接是什么,对吗?对!全局对象(浏览器上的
window
)。
var alpha = "I'm window.alpha";
var beta = "I'm window.beta";
// These, of course, reference the globals above
display("[global] alpha = " + alpha);
display("[global] beta = " + beta);
function foo(gamma) {
var alpha = "I'm alpha in the variable object for the call to `foo`";
newSection();
// References `alpha` on the variable object for this call to `foo`
display("[foo] alpha = " + alpha);
// References `beta` on `window` (the containing variable object)
display("[foo] beta = " + beta);
// References `gamma` on the variable object for this call to `foo`
display("[foo] gamma = " + gamma);
setTimeout(callback, 200);
function callback() {
var alpha = "I'm alpha in the variable object for the call to `callback`";
newSection();
// References `alpha` on the variable obj for this call to `callback`
display("[callback] alpha = " + alpha);
// References `beta` on `window` (the outermost variable object)
display("[callback] beta = " + beta);
// References `gamma` on the containing variable object (the call to `foo` that created `callback`)
display("[callback] gamma = " + gamma);
}
}
foo("I'm gamma1, passed as an argument to foo");
foo("I'm gamma2, passed as an argument to foo");
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
function newSection() {
document.body.appendChild(document.createElement('hr'));
}
[global] alpha = I'm window.alpha[global] beta = I'm window.beta--------------------------------------------------------------------------------[foo] alpha = I'm alpha in the variable object for the call to `foo`[foo] beta = I'm window.beta[foo] gamma = I'm gamma1, passed as an argument to foo--------------------------------------------------------------------------------[foo] alpha = I'm alpha in the variable object for the call to `foo`[foo] beta = I'm window.beta[foo] gamma = I'm gamma2, passed as an argument to foo--------------------------------------------------------------------------------[callback] alpha = I'm alpha in the variable object for the call to `callback`[callback] beta = I'm window.beta[callback] gamma = I'm gamma1, passed as an argument to foo--------------------------------------------------------------------------------[callback] alpha = I'm alpha in the variable object for the call to `callback`[callback] beta = I'm window.beta[callback] gamma = I'm gamma2, passed as an argument to foo
You can see the scope chain at work there. During a call to callback
, the chain is (top to bottom):
callback
foo
that created callback
Note how the variable object for the call to foo
lives on past the end of the foo
function (foo
returns before callback
gets called by setTimeout
). That's how closures work. When a function is created (note that a new callback
function object is created each time we call foo
), it gets an enduring reference to the variable object at the top of the scope chain as of that moment (the whole thing, not just the bits we see it reference). So for a brief moment while we're waiting our two setTimeout
calls to happen, we have two variable objects for calls to foo
in memory. Note also that arguments to functions behave exactly like var
s. Here's the runtime of the above broken down:
window
, Date
, String
, and all the other "global" symbols you're used to having).var
statements at global scope; initially they have the value undefined
. So in our case, alpha
and beta
.undefined
. So in our case, foo
and my utility functions display
and newSection
.var alpha = "I'm window.alpha";
. It's already done the var
aspect of this, of course, and so it processes this as a straight assignment.var beta = ...
.display
twice (details omitted).foo
function declaration has already been processed and isn't part of step-by-step code execution at all, so the next line the interpreter reaches is is foo("I'm gamma1, passed as an argument to foo");
.foo
.foo#varobj1
.foo#varobj1
a copy of foo
's reference to the variable object where foo
was created (the global object in this case); this is its link to the "scope chain."foo#varobj1
for all named function arguments, var
s, and function declarations inside foo
. So in our case, that's gamma
(the argument), alpha
(the var
), and callback
(the declared function). Initially they have the value undefined
. (A few other default properties are created here that I won't go into.)foo
(in order, beginning to end). In our case, that's callback
:
foo#varobj1
)foo#varobj1
foo
codevar alpha = ...
line, giving foo#varobj1.alpha
its value.newSection
and calls the function (details omitted, we'll go into detail in a moment).alpha
:
foo#varobj1
. Since foo#varobj1
has a property with that name, it uses the value of that property.display
and calls it (details omitted).beta
:
foo#varobj1
, but foo#varobj1
doesn't have a property with that namefoo#varobj1
for its reference to the next linkdisplay
gamma
and calls display
. This is exactly the same as for alpha
above.callback
, finding it on foo#varobj1
setTimeout
, finding it on the global objectsetTimeout
, passing in the arguments (details omitted)foo
. At this point, if nothing had a reference to foo#varobj1
, that object could be reclaimed. But since the browser's timer stuff has a reference to the callback
function object, and the callback
function object has a reference to foo#varobj1
, foo#varobj1
lives on until/unless nothing refers to it anymore. This is the key to closures.foo
, which creates foo#varobj2
and another copy of callback
, assigning that second callback
a reference to foo#varobj2
, and ultimately passing that second callback
to setTimeout
and returning.callback
function we created in foo
callback#varobj1
) for the call; it assigns callback#varobj1
a copy of the variable object reference stored on the callback
function object (which is, of course, foo#varobj1
) so as to establish the scope chain.alpha
, on callback#varobj1
callback
's codenewSection
, which it doesn't find on callback#varobj1
and so looks at the next link, foo#varobj1
. Not finding it there, it looks at the next link, which is the global object, and finds it.alpha
, which it finds on the topmost variable object, callback#varobj1
beta
, which it doesn't find until it gets down to the global objectgamma
, which it finds only one link down the scope chain on foo#varobj1
callback
callback
function, which we created in our second call to foo
.callback
gets a reference to foo#varobj2
because that's what's stored on this particular callback
function object. So (amongst other things) it sees the gamma
argument we passed to the second call, rather than the first one.callback
function objects, they and the objects they refer to (including foo#varobj1
, foo#varobj2
, and anything their properties point to, like gamma
's strings) are all eligible for garbage collection.Whew That was fun, eh?
One final point about the above: Note how JavaScript scope is determined entirely by the nesting of the functions in the source code; this is called "lexical scoping." E.g., the call stack doesn't matter for variable resolution (except in terms of when functions get created, because they get a reference to the variable object in scope when they were created), just the nesting in the source code. Consider (live copy):
var alpha = "I'm window.alpha";
function foo() {
var alpha = "I'm alpha in the variable object for the call to `foo`";
bar();
}
function bar() {
display("alpha = " + alpha);
}
foo();
alpha
的输出是什么?对!
"I'm window.alpha"
。即使我们从
alpha
调用
foo
,我们在
bar
中定义的
bar
也不会对
foo
产生任何影响。让我们快速浏览一下:
var
和声明的函数创建属性。 alpha
的值。 foo
函数对象,为其提供对当前变量对象(即全局对象)的引用,并将其放在foo
属性上。 bar
函数对象,为其提供对当前变量对象(即全局对象)的引用,并将其放在bar
属性上。 foo
。变量对象foo#varobj1
会获取foo
对其父变量对象(当然是全局对象)的引用的副本。 foo
的代码。 bar
。 bar
及其关联的变量对象bar#varobj1
的调用创建执行上下文。给bar#varobj1
分配bar
对其父变量对象的引用的副本,该对象当然是全局对象。 bar
的代码。 alpha
:bar#varobj1
上,但是那里没有该名称的属性bar
获得的链接。因此它找到了全局alpha
foo#varobj1
根本不链接到
bar
的变量对象。那很好,因为如果范围的定义是由调用函数的方式和位置定义的,我们都会发疯。 :-)一旦理解了它与函数创建有关,而函数创建是由源代码的嵌套所决定的,那么它将变得非常容易理解。
bar
的范围完全由
bar
在源代码中的位置而不是在运行时如何调用决定的原因。
this
和变量分辨率之间的关系就不足为奇了,因为全局对象(
window
)在JavaScript中有两个不相关的用途:1.如果未以设置函数的方式调用函数,则它是
this
的默认值一个不同的对象(在全局范围内),以及2。它是全局变量对象。这些是解释器与全局对象使用的无关的方面,这可能会造成混淆,因为当
this
===
window
时,变量解析似乎与
this
有某种联系,但没有。一旦您开始将其他内容用于
this
,
this
和变量分辨率便会完全断开。
关于javascript - 创建全局变量与使用JavaScript的构造函数中的变量之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6815775/
我的应用程序中有一个 settings.php 页面,它使用 $GLOBALS 来存储网络应用程序中使用的配置。 例如,他是我使用的一个示例设置变量: $GLOBALS["new_login_page
我正在尝试编译我们在 OS 类上获得的简单操作系统代码。它在 Ubuntu 下运行良好,但我想在 OS X 上编译它。我得到的错误是: [compiling] arch/i386/arch/start
我知道distcp无法使用通配符。 但是,我将需要在更改的目录上安排distcp。 (即,仅在星期一等“星期五”目录中复制数据),还从指定目录下的所有项目中复制数据。 是否有某种设计模式可用于编写此类
是否可以在config.groovy中全局定义资源格式(json,xml)的优先级,而不是在每个Resource上指定?例如,不要在@Resource Annotation的参数中指定它,例如: @R
是否有一些简单的方法来获取大对象图的所有关联,而不必“左连接获取”所有关联?我不能只告诉 Hibernate 默认获取 eager 关联吗? 最佳答案 即使有可能有一个全局 lazy=false(谷歌
我正在尝试实现一个全局加载对话框...我想调用一些静态函数来显示对话框和一些静态函数来关闭它。与此同时,我正在主线程或子线程中做一些工作...... 我尝试了以下操作,但对话框没有更新...最后一次,
当我偶然发现 this question 时,我正在阅读更改占位符文本。 无论如何,我回去学习了占位符。一个 SO 的回答大致如下: Be careful when designing your pl
例如,如果我有这样的文字: "hello800 more text 1234 and 567" 它应该匹配 1234 和 567,而不是 800(因为它遵循 hello 的 o,这不是一个数字)。 这
我一直在尝试寻找一种无需使用 SMS 验证系统即可验证电话号码(Android 和 iPhone)的方法。原因纯粹是围绕成本。我想要一个免费的解决方案。 我可以安全地假设 Android 操作系统会向
解决此类问题的规范 C++ 设计模式是什么? 我有一些共享多个类的多线程服务器。我需要为大多数类提供各种运行时参数(例如服务器名称、日志记录级别)。 在下面的伪 C++ 代码中,我使用了一个日志记录类
这个问题在这里已经有了答案: Using global variables in a function (25 个答案) 关闭 9 年前。 我是 python 的新手,所以可能有一个简单的答案,但我
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: Does C++ call destructors for global and class static
我正在尝试使用 Objective-C 中的 ArrayList 的等价物。我知道我必须使用 NSMutableArray。我想要一个字符串列表 (NSString)。关键是我的列表应该可以从我类(c
今天刚开始学习 Android 开发,我找不到任何关于如何定义 Helper 类或将全局加载的函数集合的信息,我会能够在我创建的任何 Activity 中使用它们。 我的计划是创建(至少目前)2 个几
为什么这段代码有效: var = 0 def func(num): print num var = 1 if num != 0: func(num-1) fun
$GLOBALS["items"] = array('one', 'two', 'three', 'four', 'five' ,'six', 'seven'); $alter = &$GLOBALS
我想知道如何实现一个可以在任何地方使用您自己的设置的全局记录器: 我目前有一个自定义记录器类: class customLogger(logging.Logger): ... 该类位于一个单独的
我需要使用 React 测试库和 Jest 在我的测试中模拟不同的窗口大小。 目前我必须在每个测试文件中包含这个beforeAll: import matchMediaPolyfill from 'm
每次我遇到单例模式或任何静态类(即(几乎)只有静态成员的类)的实现时,我想知道这是否实际上不是一种黑客行为,因此只是为了设计而严重滥用类和实例的原则单个对象,而不是设计类和创建单个实例。对我来说,看起
这个问题在这里已经有了答案: Help understanding global flag in perl (2 个回答) 7年前关闭。 my $test = "There was once an\n
我是一名优秀的程序员,十分优秀!