'apply'에 해당되는 글 1건

  1. 2011.11.17 javascript apply 와 call 맛보기. 2

javascript apply 와 call 맛보기.

ITWeb/개발일반 2011. 11. 17. 10:50
이전에 작성한 글중에 일부 내용이 있습니다.
http://jjeong.tistory.com/161 

javascript 에서 클래스와 상속 관련에 대한 내용으로 다뤘던 내용이구요.
여기서도 가볍게 상기시키는 관점에서 올려 봅니다.

[Function.apply]

Syntax :
  Function.apply(thisArg[, argArray])

thisArg 는 상속 받을 클래스를 지시합니다.

java 를 예로 들면
  public class OneClass extends InheritClass {
  }

여기서 OneClass 가 thisArg 가 됩니다. (OneClass 에서 InheritClass 의 member 들을 상속 받죠.)
JavaScript 에서 apply 를 사용하게 되면 thisArg 의 클래스로 상속을 해주게 됩니다.
아래 예를 보시면 이해가 쉬우실 겁니다. 

Example :

  function Car(make, model, year) {

    this.make = make;

    this.model = model;

    this.year = year;

  }

 

  function RentalCar(carNo, make, model, year) {

    this.carNo = carNo;

    Car.apply(this, new Array(make, model, year));

  }
보시면 RentalCar 클래스는 Car 클래스를 상속 받게 됩니다.
Javs 로 표현해 보면
  public class RentalCar extends Car {
  }

가 되겠죠. 



[Function.call]

Syntax :
  Function.call(thisArg[, arg1[, arg2[, ...]]])

apply 와 동일 합니다.
다만, argument 전달 방식이 array 냐 list 냐의 차이이고 동일하게 동작을 합니다. 

Example :

  function car(make, model, year) {

    this.make = make;

    this.model = model;

    this.year = year;

  }

 

  function hireCar(carNo, make, model, year) {

    this.carNo = carNo;

    car.call(this, make, model, year);

  } 


[참고사이트]
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Apply
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call



: