2017-06-25 6 views
1

すぐに呼び出される関数定義を宣言し、最後に別のカッコで "this.variable"を使用するのはなぜですか?コードは結果を "土曜日"としますが、このコードの動作を説明できますか?すぐに呼び出されたファンクション式paranthesisで "this.variable"を使用

(function(exports) { 
    var names = ["Sunday", "Monday", "Tuesday", "Wednesday", 
       "Thursday", "Friday", "Saturday"]; 

    exports.name = function(number) { 
    return names[number]; 
    }; 
    exports.number = function(name) { 
    return names.indexOf(name); 
    }; 
})(this.weekDay = {}); 

console.log(weekDay.name(weekDay.number("Saturday"))); 
// → Saturday 

ありがとう!

+0

多分それはthis'がここにグローバルオブジェクト – Bergi

+0

を指し 'ことを理解するのに役立ちますはい、真のthats。 Xotic750の答えはそれを説明しています – Adam

答えて

3

おそらくこれは理解しやすくなります。

(function() { // an object for my this, rather than the global this 
 

 
    function iife(exports) { 
 
    // only accessible within the iife context 
 
    var names = [ 
 
     'Sunday', // index number 0 
 
     'Monday', // 1 
 
     'Tuesday', // 2 
 
     'Wednesday', // 3 
 
     'Thursday', // 4 
 
     'Friday', // 5 
 
     'Saturday' // 6 
 
    ]; 
 

 
    // assign property name to the exports object with function as value 
 
    exports.name = function(number) { 
 
     return names[number]; 
 
    }; 
 

 
    // assign property number to the exports object with function as value 
 
    exports.number = function(name) { 
 
     return names.indexOf(name); 
 
    }; 
 
    } 
 

 
    // assign property weekDay to the this object with object as value 
 
    this.weekDay = {}; 
 
    // call iife with the first argument as our object's reference 
 
    iife(this.weekDay); 
 

 
    // we can see weekDay on our this object with the assigned properties 
 
    console.log(this); 
 

 
    // call the number function on the weekDay namespace 
 
    // If we had access to names: names.indexOf('Saturday') -> 6 
 
    var dayNumber = this.weekDay.number('Saturday'); 
 
    console.log(dayNumber); 
 

 
    // call the name function on the weekDay namespace 
 
    // If we had access to names: names[6] -> 'Saturday' 
 
    var dayName = this.weekDay.name(dayNumber); 
 
    console.log(dayName); 
 

 
}).call({}); // make my this object

+0

よろしくお願いします。ありがとう:) – Adam

+0

これはあなたの説明 - 関数iife(輸出){ var names = ["日曜日"、 "火曜日"、 "水曜日"、 "木曜日"、 "金曜日" 、 "土曜日"]; exports.name = function(number){ return names [number]; }; exports.number = function(name){ return names.indexOf(name); }; } this.weekDay = {}; iife(this.weekDay); console.log(weekDay.name(weekDay.number( "Wednesday"))); //→土曜日 – Adam

関連する問題