在我上一个问题之后,这个问题对我来说更准确:
例子:
function Foo() {
this.bla = 1;
var blabla = 10;
blablabla = 100;
this.getblabla = function () {
return blabla; // exposes blabla outside
}
}
foo = new Foo();
我现在的理解:
this.bla = 1; // will become an attribute of every instance of FOO.
var blabla = 10; // will become a local variable of Foo(will **not** become an attribute of every instance of FOO), which could be accessed by any instance of FOO - only if there's a method like "this.getBlabla". that's a "closer" ?
blablabla = 100; // will define a **new** (or change if exist) global(window) variable.
我理解正确吗?
此外 - 如果我在承包商中包含 var blabla = 10;
和使用它的 getblabla
函数,那么对于 Foo("foo".. .), 内存中将保存一个包含这个“私有(private)”变量的 Foo contractor 函数。或者对于 Foo 的 ALL 实例(如“foo”),它是否与私有(private)变量的位置相同的 Foo 函数?
最佳答案
只是为了关注范围,我将运行这个示例,(使用更清晰的变量)之后,我会将它连接回您的变量。
var x = "Global scope";
var y = "Not changed.";
function Foo() {
this.x = "Attribute of foo";
var x = "In foo's closure";
y = "Changed!"
this.getX = function () {
return x;
}
}
// do some logging
console.log(x); // "Global scope"
console.log(y); // "Not changed"
foo = new Foo();
console.log(y); // "Changed!"
console.log(foo.x); // "Attribute of foo"
console.log(x); // "Global scope"
console.log(foo.getX()); // "In foo's closure"
这一行:this.x
等同于this.bla
,它定义了一个Foo
对象的外部可用属性。 y
等同于 blablabla=100
然后 foo 中的 x
等同于 foo 中的 blablabla
。这是一个非常粗糙的 jsfiddle你可以跑过去看看。
关于javascript - “var” 变量、"this"变量和 "global"变量 - 在 JavaScript 构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11957191/