본문 바로가기
Development (국비 복습 )/JavaScript

자바스크립트 call()

by Puddingforever 2023. 2. 22.

함수.call(객체)

특정 함수를 실행할 때, 객체에 있는 프로퍼티값을 가져와서 실행하고 싶을 때 쓴다.

 

const person={
	talk:function(){
    	return "I talk"+this.lang;
    }
}

const me = {lang:"deutsch"};

document.write(person.talk.call(me));

1.call()함수는 객체의 프로퍼티를 이용해서 함수를 사용하기 때문에 반드시, 객체를 받아와야합니다.

2.talk()가 리턴하고 있는 this.lang에서의 this는 상속받은 객체의 프로퍼티를 이용해 사용하기 떄문에 상속받은 객체인 me를 가르킵니다.

 

 

장점

비슷한 함수를 여러개 만들지 않아도 객체의 프로퍼티를 받아서 바로 쓸 수 있다.

const house={
	clean:function(){
    	return this.name + "please clean the house";
    }
}

//둘 다 함수가 없지만 , call()함수를 이용해, 객체 프로퍼티를 빌려줄 수 있다.
const pooding = { name : "pudding"};
const puddle = { name : "puddle"};


document.write(house.clean.call(pooding)); // pudding please clean the house;
document.write(house.clean.call(puddle)); // puddle please clean the house;

 

함수에 파라메터값이 있는 경우 

const studyRoom={
	study:function(country){
    	return "I study " + this.lang + " in "+country; 
    }
}

const poodle={lang:"javascript"};

const nala ={lang:"korean"};

document.write(studyRoom.study.call(poodle,korea)); // I study javascript in korea
document.write(studyRoom.study.call(nala,germany)); // I study korean in germany

댓글