Javascript访问参数而没有传递

时间:2012-06-18 06:41:26

标签: javascript arguments

我是javascript的新手,我写了这样的代码

file myclass.js
//----------------------------------------------

function myclass () {
     this.functionA = function (value) { 
       var _this = this;
       _this.functionB ();

      }

    this.functionB = function () { 
     // here I am using the value passed to functionA when it is called.
        alert(value);
      }
}

// --------------------------------------------- ---------------------

file main.js
//-----------------------------------------   
    mc = new myclass();
    mc.functionA (45);
//-------------------------------------

在这里,我完全感到困惑,我是我的主文件,我调用了一个函数传递了一个参数,当我在functionA中调用了functionB时,我没有在functionB中传递参数,但我仍然可以访问它。 任何人都可以解释一下它是如何可能的吗?

P.S值不是全局的,不会在任何其他地方使用

谢谢

1 个答案:

答案 0 :(得分:1)

我无法重现您的行为,但我假设您在外部作用域中定义了另一个名为value的变量,该变量作为参数传递给functionA。所以你看到的不是一个,而是具有相同名称和值的两个变量

类似的东西:

function SomeConstructor() {
    var value = 'Surprise'; // * VALUE_1

    this.functionA = function (value) { // VALUE_2
        var _this = this;
        _this.functionB ();
    }

    this.functionB = function () { 
        // Here you're using the value from starred line above
        // VALUE_1
        alert(value);
    }

    // Here you also pass the same value and later assumes that 
    // functionB sees it as a parameter (VALUE_2)
    functionA(value);
}

请注意,如果您重命名value的{​​{1}}参数和外部范围中的functionA变量,则所有混淆都会消失:

value

检查您的代码,看看是否属实。


修改:编辑完问题后,我仍然无法重现您的情况。检查这是否是页面上唯一的脚本。也许,您安装了一些浏览器插件或扩展程序,可以将代码添加到您的页面中。在Chrome开发工具中,我得到:

function SomeConstructor() {
    var value1 = 'Surprise';

    this.functionA = function (value2) {
        var _this = this;
        _this.functionB ();
    }

    this.functionB = function () { 
        // Here you're using the value from starred line above
        alert(value1);
    }

    // Here it's clear that the parameter you're passing is not used at all
    functionA(value1);
}