[js] apply() 사용하기
출처 : developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
배열에 배열을 붙이기 위해 apply 사용
push 를 사용하여 요소를 배열에 추가 할 수 있습니다. push 는 가변 인수를 허용하기 때문에 여러 요소를 동시에 추가 할 수 있습니다. 그러나 push 에 배열을 전달하면 요소를 개별적으로 추가하는 대신 실제로 해당 배열을 단일 요소로 추가하므로 결국 배열 내부에 배열로 끝납니다. 그것이 우리가 원하는 것이 아니라면? 이 경우 concat 은 우리가 원하는 동작을 하지만 실제로는 기존 배열에 추가되지 않고 새 배열을 만들어 반환 합니다. 그러나 우리는 기존 배열에 추가하고 싶었습니다 ... 그럼 이제 어쩌죠? 루프를 작성 할까요? 분명히 아니죠?
방법은 apply !
var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
최대최소값
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers);
console.log(max);
// expected output: 7
const min = Math.min.apply(null, numbers);
console.log(min);
// expected output: 2
하위클래스의 인스턴스 생성할 때, 부모의 생성자를 호출하도록 한다.
function Person(arg) {
this.name = arg;
}
Person.prototype.setName = function(value){
this.name = value;
};
Person.prototype.getName = function(value){
return this.name;
};
function Student(arg) {
Person.apply(this, arguments); // 하위클래스의 인스턴스 생성할 때, 부모의 생성자를 호출하도록 한다.
}
var you = new Person("iamhjoo");
Student.prototype = you;
var me = new Student("zz"); // 하위클래스의 인스턴스 생성할 때, 부모의 생성자를 호출
console.log(me.getName());