Given this code:
function MyClass() {
var v = '1';
t开发者_StackOverflow中文版his.hi = function() {
console.log('Value of V is ' + v);
var v = '2';
console.log('Value of V is ' + v);
delete(v);
console.log('Value of V is ' + v);
}
}
When I do something like:
z = new MyClass();
z.hi();
The result I get is:
Value of V is undefined
Value of V is 2
Value of V is 2
What I want to explain is why the result is like this.
Why V is undefined (The way I understand it - and it might not be right - is that in JS it's all definition-time, not run-time, so on definition the function had it's own variable "v", but it's not defined on the first line yet though).
Why V is not deleted? Kept the same value?
How do I access the "v" with value "1" from the "one-level-up"?
I know if I use different variable name in the "hi" function, I'll be able to "see" variable "v" with the value "1" in the function. So I am kind of hiding the original one, but that still leaves the question #3 -- how do I access the "top level one"?
Thanks!
You can't delete
a variable like that.
You can't access the v
from the enclosing scope because the v
in the inner scope "hides" it. Rename it.
As to the why undefined part, what your code compiles to is:
function MyClass() {
var v = '1';
this.hi = function() {
var v;
console.log('Value of V is ' + v); // undefined!
v = '2';
console.log('Value of V is ' + v);
delete(v);
console.log('Value of V is ' + v);
}
}
As you can see the var is declared at the beginning of the scope. This is how JS works. Run it through JSLint and see for yourself.
Change it to this:
function MyClass() {
this.v = '1';
...
And make sure you always use this function with New
.
this
refers to the object that the thing is a member of. So creating this.hi
makes something in a scope totally unrelated to the function itself, but using this
for all members makes them all part of the same object (to which the function is assigned).
http://jsfiddle.net/hHvUq/
精彩评论