사용되는 위치에 따라 this 키워드에 바인드 된 객체가 달라진다.
<li onclick="printli(this)">list1</li>
<li onclick="printli(this)">list2</li>
<li onclick="printli(this)">list3</li>
<li onclick="printli(this)">list4</li>
<script>
function printli(li){
console.log(li.innerHTML);
}
</script>
👉클릭한 li에 따라 그의 innerHTML인 list1
/list2
/list3
/list4
가 출력된다
<select name="userNum" id="userNum" onchange="selectFun(this)">
<option value="1">1입니다.</option>
<option value="2">2입니다.</option>
<option value="3">3입니다.</option>
</select>
<script>
function selectFun(select){
console.log(select.value);
}
</script>
👉 select를 선택함에 따라 그의 value인 1
/2
/3
이 출력된다.
let person={
firstName: "John",
lastName: "Doe",
fullName: function(){
return this.firstName + "" + this.lastName;
},
}
console.log(person.fullName());
👉 해당 object의 firstName과 해당 object의 lastName을 반환하여 더한 값을 fullName key의 value에 저장했다.
this를 특정 값으로 지정할 수 있는 메소드
함수명.call(변수,함수의 매개변수)
this를 함수에서 사용하고 싶을때, 아래와 같이 전달한다.
let stu={
name:"B",
age:30
}
function printName(){
console.log(this.name)
}
printName()
//👉 ""
printName.call(stu)
//👉 "B"
function objUpdate(name,age){
this.name= name;
this.age= age;
}
objUpdate.call(student1,"green",30);
console.log(stu)
//👉 "green"
함수명.call(변수,함수의 매개변수)
this를 함수에서 사용하고 싶을때, 아래와 같이 전달한다.
함수에 매개변수를 입력할 때, 배열로 입력한다.
objUpdate.apply(student1,["green",30]);
console.log(stu)
//👉 "green"
❗ apply는 배열을 펼쳐넣는다.
때문에 apply를 지정할 때에는 numArr와 같이 지정해야한다.
❗ call은 배열을 펼쳐넣지 않으므로 ...numArr로 작성해야한다.
const numArr=[1,2,3,4,5];
let maxNumber= Math.max.apply(null, numArr);
let maxNumber2= Math.max.call(null, ...numArr);
함수.bind(변수)
this의 값을 영구적으로 변경한다.
const aa={
x:50
}
const newFun= aa.getX;
const nnewFun= newFun.bind(aa);
//newFun= function(){return this.x;}
console.log(newFun());
//👉undefined
console.log(nnewFun());
//👉50
함수.bind(this)
//👉this를 "나 자신"으로 지정한다.