0

私は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を呼び出して引数を渡しました。functionAでfunctionBを呼び出したとき、functionBで引数を渡していないのに、アクセスできます。どうしてそれが可能かを誰かが親切に説明できますか?

PS値はグローバルではなく、他の場所では使用されません

ありがとう

4

1 に答える 1

1

I can't reproduce your behavior but I assume that you have another variable defined in the outer scope called value which is passed to functionA as a parameter. So what you see is not one but two variables with the same names and values.

Something like that:

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

Notice that if you rename value parameter for functionA and the value variable in the outer scope all confusion goes away:

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

Check your code and see if that's the case.


Edit: After you've edited your question I still can't reproduce your case. Check if that's the only script on a page. Perhaps, you have some browser addons or extensions installed that add the code to your page. In Chrome Dev Tools I get:

"ReferenceError: value is not defined"
于 2012-06-18T06:58:28.117 に答える