例如:JavaScript构造函数中的“var”变量会发生什么?
function Foo() {
this.bla = 1;
var blabla = 10;
blablabla = 100;
this.getBlabla = function() {
return blabla; // exposes blabla outside
}
}
foo = new Foo();
原题:
我知道,喇嘛将被分配到富的每一个实例。 blabla会发生什么?
新的问题:
我现在明白了:
this.bla = 1; // will become an attribute of every instance of FOO.
var blabla = 10; // will become a local variable of Foo(**not** 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".
blablabla = 100; // will define a **new** (or change if exist) global(window) variable.
Did i understand correctly?
你编辑的例子是正确的 - 除了'blabla'对'Foo'的每一个实例都是唯一的。所以如果'Foo'看起来像'function Foo(number){var blabla = number; this.bla = 37; this.getBlaBla = function(){return blabla; }; }'然后'myFoo = new Foo(32);''和'yourFoo = new Foo(47);'对于'.getBlaBla()'会有完全不同的值。 'myFoo.getBlaBla()=== 32; yourFoo.getBlaBla()=== 47;'重要的是要记住,即使它是一个“本地范围的值”,它对于每个实例都是唯一的,并且不会成为任何Foo读/写的相同值以共同的方式。 – Norguard 2012-08-16 13:48:26