달나라 노트

Google Apps Script : method overwrite, method overriding, method 변경, method 덮어씌우기 본문

Google Apps Script

Google Apps Script : method overwrite, method overriding, method 변경, method 덮어씌우기

CosmosProject 2022. 11. 28. 23:48
728x90
반응형

 

 

 

Class를 어떤 변수에 할당하여 인스턴스화했을 때 이 객체는 Class가 가진 method와 동일한 기능을 가지는 method를 호출할 수 있게 됩니다.

 

근데 만약에 객체에서 method의 내용을 변경하고싶으면 어떻게해야할까요?

 

 

예시를 통해 봅시다.

 

 

class Cat {
  constructor(name, age, weight, color) {
    this.name = name;
    this.age = age;
    this.weight = weight;
    this.color = color;
    this.species = 'mammal';
  }

  sound() {
    Logger.log('Moew~');
  }
}

function myFunction(){
  var my_cat = new Cat(name='Kitty', age=5, weight=4.5, color='white');

  my_cat.sound();
}


-- Result
Moew~

 

위 예시는 Cat class를 생성한 후 my_cat 변수에 할당하여 my_cat 변수를 객체로 만들고 있습니다.

 

Cat class에 sound()라는 method가 있고 이를 my_cat에서도 당연히 호출할 수 있죠.

 

근데 고양이의 울음소리가 대부분 비슷하긴 하지만 조금 다를 수 있을겁니다.

따라서 sound() method의 결과로 출력되는 고양이 울음소리를 좀 바꿔보고싶습니다.

 

이럴 땐 아래처럼 코드를 고치면 됩니다.

 

class Cat {
  constructor(name, age, weight, color) {
    this.name = name;
    this.age = age;
    this.weight = weight;
    this.color = color;
    this.species = 'mammal';
  }

  sound() {
    Logger.log('Moew~');
  }
}

function myFunction(){
  var my_cat = new Cat(name='Kitty', age=5, weight=4.5, color='white');

  my_cat.sound = function() {
    Logger.log('Mew~ Moew~');
  }

  my_cat.sound();
}



-- Result
Mew~ Moew~

 

위 결과를 보니 마지막 부분에 my_cat.sound() 처럼 sound() method를 호출하고 있는데 그 결과는 이전에 봤던 예시와 다르죠.

 

 

 

 

 

 

  var my_cat = new Cat(name='Kitty', age=5, weight=4.5, color='white');

  my_cat.sound = function() {
    Logger.log('Mew~ Moew~');
  }

  my_cat.sound();

 

이 부분을 봅시다.

Cat class를 이용해서 my_cat 객체를 생성했는데

sound() method를 호출하기 전에 my_cat.sound에 새로운 함수를 할당하고 있습니다.

 

그리고 이 함수의 내용은 Mew~ Moew~ 라는 글자를 출력해주는 것이죠.

 

my_cat에는 sound라는 method가 있고 sound method에 새로운 function을 할당하면 기존의 sound method가 가진 기능은 없어지고 새롭게 할당된 function이 sound method의 기능으로서 덮어씌워집니다.

마치 sound method의 기능을 새로운 기능으로 덮어씌워버리는 것과 같죠.

 

이것을 method overwrite(덮어씌우기) 또는 method overriding(덮어씌우기)라고 합니다.

 

 

 

 

 

 

728x90
반응형
Comments