Javascript_ this(2) call, apply

JOO·2021년 11월 11일
0

javascript기초

목록 보기
10/15

Javascript_ call, apply

this에 바인딩된 값이 원래 정해진 규칙을 깨야 한다면 해당 문법 사용할 수 있음.

call 메서드

let obj = {
	a: -1,
 	method: function(x, y){
 		console.log(this.a, x, y)
 	}
 
obj.method(2,3); // 1 2 3 
obj.method.call({a: 4}, 5, 6); // 4 5 6

apply 메서드

let func = function(x) {
 console.log(this, x);
}
func.apply({x : 1{, [4, 5, 6]) // {x: 1} 4 5 6  
 
let obj = {
 a: 1,
 method : function(x, y){
 	console.log(this.a, x, y)
 }
 };

obj.method.apply({a: 4}, [5, 6]); // 4 5 6

생성자 내부에서 다른 생성자를 호출

function Person(name, gender) {
 this.name = name;
 this.gender = gender;
}

function Student(name, gender, school) {
 Person.call(this, name, gender);
 this.school = school;
}

function Employee(name, gender, company) {
 Person.apply(this, [name, gender]);
 this.company = company;
}
let by = new Student('주', 'male', '유치원')
let jn = new Employee('재난', 'male', '초등학교')
profile
개발공부 기록

0개의 댓글

관련 채용 정보