例如: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