JavaScript var 可见性

问题描述 投票:0回答:3

给出这段代码:

function MyClass() {
    var v = '1';
    this.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);
    }
}

当我做类似的事情时:

z = new MyClass();
z.hi();

我得到的结果是:

Value of V is undefined 
Value of V is 2
Value of V is 2

我想解释的是为什么结果是这样的

  • 为什么 V 是未定义的(我的理解方式 - 也许不正确 - 是在 JS 中,它都是定义时的,而不是运行时的,所以在定义时,函数有它自己的变量“v”,但它是但尚未在第一行定义)。

  • 为什么V没有被删除?保持相同的值?

  • 如何从“上一层”访问值为“1”的“v”?

  • 我知道如果我在“hi”函数中使用不同的变量名称,我将能够“看到”函数中值为“1”的变量“v”。所以我隐藏了原始的,但这仍然留下了问题#3 - 我如何访问“顶级”?

谢谢!

javascript function oop visibility
3个回答
2
投票

你不能

delete
这样的变量

您无法从封闭范围访问

v
,因为内部范围中的
v
“隐藏”了它。重命名它。


1
投票

至于为什么未定义的部分,您的代码编译后的结果是:

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);
    }
}

如您所见,var 是在作用域的开头声明的。这就是 JS 的工作原理。通过 JSLint 运行它并亲自查看。


0
投票

改成这样:

function MyClass() {
    this.v = '1';
...

并确保您始终使用此功能

New

this
指的是事物所属的对象。因此,创建
this.hi
会使作用域中的某些内容与函数本身完全无关,但对所有成员使用
this
会使它们成为同一个对象(函数分配给的对象)的一部分。

http://jsfiddle.net/hHvUq/

© www.soinside.com 2019 - 2024. All rights reserved.