Map 전역변수로 사용하는 방법 질문

조회수 2130회

function addTab에서 사용시 Uncaught TypeError: titleMap.put is not a function 에러 발생

전역변수 바로 아래서 사용시 정상적으로 작동... 전역변수로 사용하려면 어떻게 해야하나요?

$(document).ready(function() {
    // Map 공통
    Map = function(){
      this.map = new Object();
    };   
    Map.prototype = {   
        put : function(key, value){   
            this.map[key] = value;
        },   
        get : function(key){   
            return this.map[key];
        },
        containsKey : function(key){    
         return key in this.map;
        },
        containsValue : function(value){    
         for(var prop in this.map){
          if(this.map[prop] == value) return true;
         }
         return false;
        },
        isEmpty : function(key){    
         return (this.size() == 0);
        },
        clear : function(){   
         for(var prop in this.map){
          delete this.map[prop];
         }
        },
        remove : function(key){    
         delete this.map[key];
        },
        keys : function(){   
            var keys = new Array();   
            for(var prop in this.map){   
                keys.push(prop);
            }   
            return keys;
        },
        values : function(){   
         var values = new Array();   
            for(var prop in this.map){   
             values.push(this.map[prop]);
            }   
            return values;
        },
        size : function(){
          var count = 0;
          for (var prop in this.map) {
            count++;
          }
          return count;
        }
//        ,
//        toStrong:function(){bar s=[];
//          for(var prop in this.map) s.push(prop+':'+this.map[prop]);
//          return s.join(',');
//        }
    };

    $('#pageTab').on('click', ' li a .close', function() {
      var tabId = $(this).parents('li').children('a').attr('href');
      $(this).parents('li').remove('li');
//      titleMap.remove(tabId);
      $(tabId).remove();
      reNumberPages();
      $('#pageTab a:first').tab('show');
    });

    $("#pageTab").on("click", "a", function(e) {
      e.preventDefault();
      $(this).tab('show');
    });
  });

  var pageNum = 1;
  var titleMap = new Map();
  titleMap.put("key","data");
        console.log(titleMap);

  function reNumberPages(){
    pageNum = 1;
    var tabCount = $('#pageTab > li').length;
    $('#pageTab > li').each(function(){
      var pageId = $(this).children('a').attr('href');
      if(pageId == "#page1"){
        return true;
      }
      pageNum++;
      //tab header Title
      $(this).children('a').html(titleMap.get(pageId)+'<button class="close" type="button" ' + 'title="Remove this page">x</button>');
    })
  }


  function addTab(title){
    pageNum++;
    var pageId = '#page'+pageNum;
    titleMap.put(pageId, title);
//    titleMap.put(pageId,title);
    // tab header title
    $('#pageTab').append($('<li><a href="#page' + pageNum + '">' + title +'<button class="close" type="button" ' +'title="Remove this page">x</button>' +'</a></li>'));
    $('#pageTabContent').append($('<div class="tab-pane" id="page' + pageNum +'">Content page' + pageNum + '</div>'));
    $('#page' + pageNum).tab('show');
  }
  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 소스를 돌려보니 titleMap에 put 메서드가 없다고 에러가 나는데요. 이걸 물어보신게 맞다고 가정하고 말씀드리면,

    var titleMap = new Map();
    titleMap.put("key","data");
    

    위 코드가 실행되는 시점이 Map에 put 메서드를 추가하는 시점보다 빨라서 그렇습니다. 첨부하신 코드를 보면:

    $(document).ready(function() {
        // Map 공통
        Map = function(){
          this.map = new Object();
        };   
        Map.prototype = {   
            put : function(key, value){   
                this.map[key] = value;
            },   
    
        // 생략
    

    이렇게 되어 있는데, 이 부분은 HTML 랜더링 이후에나 실행될테니 titleMap에 put이 없다고 나오는 것이죠. 그러니 아래처럼 수정하세요:

    // Map 공통
    Map = function(){
      this.map = new Object();
    };   
    Map.prototype = {   
      put : function(key, value){   
        this.map[key] = value;
      },   
      get : function(key){   
        return this.map[key];
      },
      containsKey : function(key){    
        return key in this.map;
      },
      containsValue : function(value){    
        for(var prop in this.map){
          if(this.map[prop] == value) return true;
        }
        return false;
      },
      isEmpty : function(key){    
        return (this.size() == 0);
      },
      clear : function(){   
        for(var prop in this.map){
          delete this.map[prop];
        }
      },
      remove : function(key){    
        delete this.map[key];
      },
      keys : function(){   
        var keys = new Array();   
        for(var prop in this.map){   
          keys.push(prop);
        }   
        return keys;
      },
      values : function(){   
        var values = new Array();   
        for(var prop in this.map){   
          values.push(this.map[prop]);
        }   
        return values;
      },
      size : function(){
        var count = 0;
        for (var prop in this.map) {
          count++;
        }
        return count;
    }
    //    ,
    //    toStrong:function(){bar s=[];
    //      for(var prop in this.map) s.push(prop+':'+this.map[prop]);
    //      return s.join(',');
    //    }
    };
    
    $(document).ready(function() {
      $('#pageTab').on('click', ' li a .close', function() {
        var tabId = $(this).parents('li').children('a').attr('href');
        $(this).parents('li').remove('li');
        //      titleMap.remove(tabId);
        $(tabId).remove();
        reNumberPages();
        $('#pageTab a:first').tab('show');
      });
    
      $("#pageTab").on("click", "a", function(e) {
        e.preventDefault();
        $(this).tab('show');
      });
    });
    
    var pageNum = 1;
    var titleMap = new Map();
    titleMap.put("key","data");
    console.log(titleMap);
    
    function reNumberPages(){
      pageNum = 1;
      var tabCount = $('#pageTab > li').length;
      $('#pageTab > li').each(function(){
        var pageId = $(this).children('a').attr('href');
        if(pageId == "#page1"){
          return true;
        }
        pageNum++;
        //tab header Title
        $(this).children('a').html(titleMap.get(pageId)+'<button class="close" type="button" ' + 'title="Remove this page">x</button>');
      });
    }
    
    function addTab(title){
      pageNum++;
      var pageId = '#page'+pageNum;
      titleMap.put(pageId, title);
      //    titleMap.put(pageId,title);
      // tab header title
      $('#pageTab').append($('<li><a href="#page' + pageNum + '">' + title +'<button class="close" type="button" ' +'title="Remove this page">x</button>' +'</a></li>'));
      $('#pageTabContent').append($('<div class="tab-pane" id="page' + pageNum +'">Content page' + pageNum + '</div>'));
      $('#page' + pageNum).tab('show');
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)