JavaScript Why return function in a function?

前端 未结 6 1678
青春惊慌失措
青春惊慌失措 2020-12-18 04:17
var favoriteColor = \"blue\";
function colorGenerator(color) {
    return function () { return color; };
}
var getColor = colorGenerator(favoriteColor);
6条回答
  •  一向
    一向 (楼主)
    2020-12-18 04:59

    most time we return funciton, our target is limit variable scope and keep state. so your code should be:

    function colorGenerator(color) {
        var favoriteColor = color; //here keep state
      return function (c) { return c===favoriteColor; };
    }
    var isorange = colorGenerator("orange"); //because you only call colorGenerator one time, so function isorange keep the state : 'orange'
    isorange('black') //here return false
    isorange('orange') //here return true
    

提交回复
热议问题