1

私は次のコードを持っています:

module = {

        submodule: {

            value: 'foo',

            init: function(){
                console.log(module.submodule.value);
            }

        }

    };

コンソールを介してこのコードをテストしているときは正しい値を取得しますが、関数内のステートメントでundefined同じコードを使用しているときは 正しい値しか取得しません。これは一般的な初心者や些細な質問の1つだと思いますが、現在、これに頭を悩ませることはできません:)returninit

4

2 に答える 2

3

Console return undefined because your method doesn't return any value and the console always output the return of a function when called from the console.

If you add return true in your init method it will output the value and true.

It's only the behaviour of the console you are seeing nothing wrong.

于 2012-04-25T09:16:57.780 に答える
3

あなたの関数は何も返していません。コンソールには、関数の戻り値のみが表示されます。関数が何かを返す必要はありませんが、コンソールに最終的に「値」を表示させたい場合は、

module = {

        submodule: {

            value: 'foo',

            init: function(){
                return module.submodule.value;
            }

        }

    };

何が起こるかというと、各関数が何かを「返す」ということです。この何かは、他の場所で入力として使用できます。例えば、

function getName(){
return "Manish";
}

alert(getName()) //will display "Manish" sans quotes

次のようなことができます

function sin(theta){
//do some math voodoo, store result in "result"
return result;
}
alert((sin(theta)*sin(theta)-5)/Math.sqrt(1-sin(theta)*sin(theta))//random thingy

しかし、関数に何かを返させない (またはreturn;すぐに関数を終了できるので使用する) と決めた場合、未定義の値が返されます。戻り値を使用しようとしない限り、これは問題ありません。

于 2012-04-25T09:23:54.833 に答える