Javascript在不向外传递的情况下访问参数
我是javascript新手,我写过这样的代码Javascript在不向外传递的情况下访问参数,javascript,arguments,Javascript,Arguments,我是javascript新手,我写过这样的代码 file myclass.js //---------------------------------------------- function myclass () { this.functionA = function (value) { var _this = this; _this.functionB (); } this.functionB = function () {
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);
//-------------------------------------
在这里,我完全搞不清楚我是我的主文件,我调用了一个function并传递了一个参数,当我在function中调用functionB时,我还没有在functionB中传递参数,但我仍然能够访问它。
谁能解释一下这是怎么可能的
p.S值不是全局值,不在任何其他地方使用
谢谢我无法重现您的行为,但我假设您在外部范围中定义了另一个变量,名为
value
,它作为参数传递给function
。因此,您看到的不是一个变量,而是两个具有相同名称和值的变量
诸如此类:
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);
}
请注意,如果重命名function
的value
参数以及外部范围中的value
变量,所有混淆都会消失:
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);
}
检查你的代码,看看是否是这样
编辑:编辑完问题后,我仍然无法再现您的案例。检查这是否是页面上唯一的脚本。也许,您安装了一些浏览器插件或扩展,可以将代码添加到页面中。在Chrome开发工具中,我得到:
"ReferenceError: value is not defined"
这叫做结束。请在此阅读更多信息:谢谢您的回答,但这不是结束语。因为我不是在functionB中定义functionB。我只是打电话给它,我建议你创建一个完全有效的例子,展示意外的行为。此代码段不足以从中工作。Thank@nhahdh是否有办法找出它所指的任何当前时间确保,
值
未声明为全局-即使在全局范围内有var
(是否存在此
指向窗口对象的位置)